开发者

mvc dropdownlist - capturing change event without attaching the event handler

开发者 https://www.devze.com 2023-01-24 10:57 出处:网络
I know I can attach change event to html.dropdownlist in mvc as shown below: $(\'#ddList\').change(function() {

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 ddListChan开发者_JAVA百科ge() {
        alert("test");
    }

Also, is one more approach more preferred than the other?


Yes, 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

0

精彩评论

暂无评论...
验证码 换一张
取 消