I am loading the value of string myvalue (global string) in array arr in javascript by
function hello()
{
alert("hi");
var arr=[<% myvalue %>];
alert(arr);
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myvalue="1234";
Page.ClientScript.RegisterStartupScript(GetType(), "whatiskey", "hello();", true);
}
and updating myvalue on listbox1.item select and calling method which updates value of arr, but javascript arr does not load the new value
you have to put double quotes and write it like:
var arr=["<%=myvalue %>"];
or more better way :
var arr= new Array();
arr.push("<%=myvalue %>");
Register ListBox1 as partial post back element could also be one of the reason.
are you able debug, that ListBox1_SelectedIndexChanged is being called.
You need to something like below to stop this from multiple time registered, this can one of the reason not to call hello(). Use F12 to investigate the rendered HTML.
// Check to see if the client script is already registered.
if (!Page.ClientScript.IsClientScriptBlockRegistered(cstype, csname2))
{
Page.ClientScript.RegisterStartupScript(GetType(), "aNewKey", "hello();", true);
}
Related
I have tried below approach.
I used one hidden field on aspx page named hdnTime.
Then I assigned value to hidden field in javascript function.
<script type='text/javascript'>
function getLocalTimeZone() {
document.getElementById('ctl00_bcr_hdnTime').value = 10;
var hidden = document.getElementById('ctl00_bcr_hdnTime');
var timezone = String(new Date());
hidden.value = timezone.substring(timezone.lastIndexOf('(') + 1).replace(')', '').trim();
}
Then on C# page load I tried below code.
ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "getLocalTimeZone()", true);
string test = hdnTime.Value;
But I am getting blank value for hdnTime.
Please let me know if I missing something here.
Page_Load event is executed before document.ready so anything set in document.ready won't be available in Page_Load event
You can set value on click of a button than in c# you can get that value.
I am using an external JavaScript file which will give me a message when a Dropdown list value is not selected. It is set 'Select' by default. I have tried a lot of things I found while searching, but it is not running on my site. I am using Visual studio 2013 with 4.5 frame work.
Below is the code I have tried.
function unicollege()
{
var ddlObject = document.getElementById("<%=ddlType.ClientID%>");
var selectedValue = ddlObject.options[ddlObject.selectedIndex].value;
var e = document.getElementById("ddlLocation");
var selectedLocation = e.options[e.selectedIndex].value;
// .option and .value property are not available in my program.
}
Here is what needs to be in your page to use the external javascript file:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(
this,
typeof(Page),
"",
ResolveClientUrl("JavaScript1.js"));
}
In your aspx markup use a variable for your ddl to reference in your external javascript file:
<script type="text/javascript">
var ddl = "<%=ddlList.ClientID%>";
</script>
and in your external javascript file:
/// <reference path="WebForm1.aspx" />
function unicollege() {
var ddlObject = document.getElementById(ddl);
var selectedValue = ddlObject.options[ddlObject.selectedIndex].value;
}
you dont really need to think this much complex.
i do these kind of work every day a thousand times.
function unicollege()
{
var ddlSelectedValue = document.getElementById("ddlType").value;
}
this i just sent u after testing..it is going to work perfectly fine and i am doing it for a long time.however be careful about the postback problems if they happen.
I've look an found only a similar post and didn't really answer my question or maybe they did but I didn't understand. The post I read was this one: Why does this javascript variable I'm creating via C# only get updated once?
I'm using a paged gridview and every time it's object data source runs the SelectCountMethod, I use the returning value on javascript. But, I've noticed that even thought that same returned value changes, on the server side. On javascript this value doesn't update.
My program is quite long but I'll use a basic example and hopefully some of you will understand it.
Client side:
function SomeFuntion()
{
alert("<%=num%>");
}
Server side:
//Global variable
Public Static int num = 0;
Public int SelectCountMethod()
{
var num = SomeMethod(); //Returns int
return num;
}
For example, on the server side num returns 60 and then this value updates to 7. On the server side num equals 7 but on the client side it's still 60. Is there a way to update the client sides value?
I apologies for my poor typing skills, English is not my native language.
Some examples might be helpful and thanks in advance.
I noticed that it doesn't mater where I update this variable(on selectCount method or any other method), on the client side doesn't update.
Taking a look at your client-side code, the "<%=num%>" is actually run on the server. If you examined the source in your browser, what you'll see is:
function SomeFuntion()
{
alert("60");
}
As you can see--there is no variable to update. In order to see that "60" change to "7", you'd have to refresh the client to pick up the new value that the server has for "num".
You could modify your JS method like this
var myMsg = <%=num%>;
function SomeFuntion()
{
alert(myMsg);
}
and in the codebehind
public int num = 60;
public int SelectCountMethod()
{
num = SomeMethod(); //Returns int
ScriptManager.RegisterStartupScript(this,
this.GetType(),
"Funct",
"myMsg = " + num + ";",
true);
return num;
}
So every time your method SelectCountMethod() is called, your JS variable myMsg get a new value because of the line ScriptManager.RegisterStartupScript
Without your server side code, we won't be able to find the ideal solution. However, you could potentially do the following:
Use a Hidden Field to store the value.
Use a global variable for the page, to pass the value to global variable in your JavaScript.
The easiest would be the Hidden Field, the reason is you can easily modify the data on both Client and Server without any real issues. You'll want to ensure that you do not modify the state to often.
<input type="hidden" id="hdTimer" runat="server" />
Then you can do your JavaScript, such as:
$('#Example').on('change', function () {
$('#hdTimer').val('60');
});
Now throughout the Client code you'll be able to modify the field with no issues, but when you need to submit a form, for a PostBack. You can use the field server side:
var content = hdTimer.value;
As I noted though, excessive cross manipulation may cause an issue at some point. Depending on the complexity. Your other approach would be the Global.
// Server Side
var example = 60;
protected void Page_Load(object sender, EventArgs e)
{
}
So this Global will hold the value, but when you reinitialize the value at Page Load it will hold be able to push an updated value to your JavaScript:
//Client Side:
var example = '<%= example %>';
The key though, will be to ensure you properly reinitialize the value.
When you do a PostBack your page is reinitialized, which can modify values on you if you aren't aware. This is incredibly important.
Use an HttpHandler and jQuery. Google is your friend, there are several examples on SO as well.
I found a possible solution, inefficient, but it will have to do. I have a search textbox that every time the search button is clicked, updates the grid view with the retrieved data from a data base. When the Onclick is called it binds the data source with the gridView. What I did was call the SelectCountMethod again right below the binding and used the same parameters I had stored on the Object data source as paramaters for the selectCountMethod. Then the amount returned by the selectCount I stored it on a hiddenField and that's it.
//Global variables
string _param1 = string.Empty,
_param2 = string.Empty;
//On click method for search btn
protected void OnSearch(object sender, EventArgs e)
{
gv.DataBind();
someHiddenField = SelectCountMethod(param1, param2);
}
protected void OnSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
try
{
e.InputParameters["Param1"] = param1;
_param1 = param1
e.InputParameters["Param2"] = param2;
_param2 = param2;
}
catch (Exception ex)
{
cvServerError.IsValid = false;
cvServerError.ErrorMessage = ex.Message;
}
}
I'm using a set of UserControls on a ASP.NET application which I'm maintaining.
I have a page which renders a set of custom UserControls. On one of these controls, lets say ucA, I may have a little Javascript Popup which render another UserControl and let's call this one ucB.
On ucA I've defined a public property which sets or gets values from a hiddenField defined in ucA:
<asp:HiddenField ID="hidWorkDirName" runat="server" />
and the property definition:
public string _hidWorkDirName
{
get { return hidWorkDirName.Value; }
set { hidWorkDirName.Value = value; }
}
My ucB only shows a Textbox which, upon submit, should set the value of the hidWorkDirName:
protected void btnSubmit_Click(object sender, EventArgs e)
{
ucA parent = (ucA)this.Parent; //this, being ucB
parent._hidWorkDirName = txtName.Text; //the TextBox value being set on ucA
}
While debugging I can see that the value is set correctly.
Now, ucA also has a Submit button (both submits are for different things) on which I want to read the value of the hidWorkDirName. But no matter what I try the value I get is always an empty string as if nothing had been set.
I've tried reading the value directly from the hiddenField and from the property itself (_hidWorkDirName) but I never get the value I've set previsouly.
Why is this happening?
This is because the Hiddenfield hidWorkDirName could get reset during the Page_Load. Try a different approach using ViewState.
Here's your property with ViewState
public string _hidWorkDirName
{
get
{
if (ViewState["WorkDirName"] != null)
{
return (string)ViewState["WorkDirName"];
}
return string.Empty;
}
set
{
ViewState["WorkDirName"] = value;
}
}
I'm new to jQuery right now I'm using Telerik asp.net MVC control along with Razor view engine. Here is a code snippet from my view.
Html.Telerik().ComboBox().Name("cmb")
.AutoFill(true)
.DataBinding(binding => binding.Ajax().Select("_loadData", "MyController").Cache(false))
.ClientEvents(ce => ce.OnLoad("cmbLoaded"))
function cmbLoaded(e) {
var ComboBox = $("#cmb").data("tComboBox");
//do stuff here
}
Ok this what I'm trying to do I want to send extra parameter to the telerik Combobox event say cmbLoaded event handler. how can i do that.
thanks in advance.
It's been awhile but a ran into a similar situation. The string you pass as a parameter to the OnLoad event is a Javascript function reference, so you can pass something like:
.ClientEvents(ce => ce.OnLoad("function(e) { cmbLoaded.call(this,e," + Model.Id + "); }"))
Then your Javascript function signature would change to:
function cmbLoaded(e, id)
You want to submit extra parameter when your combo is fetching the data from the server?
Then you can send it with the help of the OnDataBinding event.
For example:
function onComboBoxDataBinding(e){
e.data={extraParameter:"Cool"};
}
you can do it by defining some variables in a code block, and then use them in your javascript event handler. Here is an example:
#{
string myPar1 = "some text";
int myPar2 = 10;
}
<script type="text/javascript">
function cmbLoaded(e, '#myPar1' #myPar2) {
var ComboBox = $("#cmb").data("tComboBox");
//do stuff here
}
</sciprt>