I know I can attach change event to html.dropdownlist in mvc as shown below:
$('#ddList').change(function() {
var value = $(this).val();
});
However, is there a way I can do it more like
<%=Html.DropDownList("ddList", Model.dropDown, new { @class = "Ddl", change = "ddListChange" })%>
js function below:
function ddListChange() {
alert("test");
}
Also, is one more approach more preferred than the other?
I know I can attach change event to html.dropdownlist in mvc as shown below:
$('#ddList').change(function() {
var value = $(this).val();
});
However, is there a way I can do it more like
<%=Html.DropDownList("ddList", Model.dropDown, new { @class = "Ddl", change = "ddListChange" })%>
js function below:
function ddListChange() {
alert("test");
}
Also, is one more approach more preferred than the other?
Share Improve this question asked Nov 12, 2010 at 0:59 TPRTPR 2,57710 gold badges41 silver badges66 bronze badges1 Answer
Reset to default 4Yes, you were close, as the onchange
attribute was what you were looking for.
<%= Html.DropDownList("ddList", Model.dropDown, new { @class = "Ddl", onchange = "ddListChange" }) %>
jQuery skips the on
part of the event names in its methods/parameters for events, e.g. .click(...) / .bind('click',..)
equals the onClick
attribute.
Binding event handlers using javascript itself is the preferred way. Just like you separate styling into separate CSS files, you separate scripting into your own scripting files. This allows the HTML file to be cleaner and easier to read, in addition to separating the concerns of prensentation and whatever your scripts is doing. It also makes it easier for you page to degrade gracefully (work even if scripts aren't enabled).
Here is one article discussing the issue