user3010406 user3010406 - 28 days ago 12
ASP.NET (C#) Question

change event in jQuery, Used For SelectedIndexChanged in ASP.NET DropDown List

I am developing a server control in C#. I am trying to read via jQuery when the selectedindexchanges on a drop down menu.

All my research has alluded to using the change event. As a result, I built a simple test via an alert to see whether this event gets called correctly. Here is my script:

var builder = new StringBuilder();
builder.Append("$(document).ready(function() {");
builder.Append("$($='_ddlMyTest').change(function() {");
builder.Append("alert('hello');");
builder.Append("}");
builder.Append(");");
builder.Append("}");
builder.Append(");");


I call this script in my control to register startup scripts:

ScriptManager.RegisterStartupScript(Page, GetType(), "myfunction", String.Format("<script type='text/javascript'> {0}</script>", builder), false);


I know jQuery is registered correctly, and the above is registered correctly if I just throw an alert in the
$(document).ready
I do see it in my browser.

My rendered HTML for that element looks like a normal select. I have also tried passing in the ClientID rather than using the
$='_ddlMyTest'
to no effect. I have made sure after that this match.

My question is, does this change event work for when the index is changing in an asp.net dropdown?

Answer

One very important thing to note here is that, in the browser, and from the perspective of JavaScript, there is no such thing as "an ASP.NET DropDown". The HTML element is a select, no different from any other select.

What concerns me is this selector:

$($='_ddlMyTest')

I've never seen that $= syntax before, and it's not clear to me what that's even intending to do. If the id of the client-side element is _ddlMyTest then the selector would be:

$('#_ddlMyTest')

If, as you suggest, the client-side id is different (WebForms has a history of doing that), then you'd need to make sure you're using that id. How did you attempt that? I'm not really certain how you'd get that from within the context of that StringBuilder in the server-side code, but presumably if there's a ClientID property then it would look something like:

builder.Append("$('#" + ClientID + "').change(function() {");

or:

builder.Append(string.Format("$('#{0}').change(function() {", ClientID));

(not sure if the { characters in the JavaScript code would mess with string.Format though) or:

builder.Append("$('#");
builder.Append(ClientID);
builder.Append("').change(function() {");

Whichever you think is more clear, they all essentially should produce the same result with minor performance differences. The point being that it would need to happen in the server-side code since the rendered JavaScript has no knowledge of the ClientID property.

Comments