MVC 中的下拉列表 onchange 事件和 AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2236621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:51:14  来源:igfitidea点击:

DropDown list onchange event and AJAX in MVC

asp.net-mvcajax

提问by Jaqen H'ghar

I have a code black in my MVC view as follows:

我的 MVC 视图中有一个黑色代码,如下所示:

<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
     { %>
          <%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
                 <%} %>

I want to set the value of ViewData["selected"] so that i can send it to the desired action. Can anyone please suggest how can i do this?

我想设置 ViewData["selected"] 的值,以便我可以将它发送到所需的操作。任何人都可以请建议我该怎么做?

thanks!

谢谢!

回答by Johannes Setiabudi

Instead of using a form, why not use a jQuery onChange event on your drop down?

除了使用表单,为什么不在下拉列表中使用 jQuery onChange 事件?

$(document).ready(function() {
    $("#ddl").change(function() {
        var strSelected = "";
        $("#ddl option:selected").each(function() {
            strSelected += $(this)[0].value;
        });
        var url = "/Home/MyAction/" + strSelected;

        $.post(url, function(data) {
            // do something if necessary
        });
    });
});

回答by Ricky Supit

ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).

ViewData 不是将数据传回服务器端的地方。表单标签内的 html 输入控件的值在 action 方法中很方便。您可以从各种类型的操作方法参数(模型、表单集合等)中获取这些值。

Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.

这是免费的 asp.net mvc 电子书教程的链接。是asp.net mvc 的好资源。

回答by orsini

Found solution at this post it is just small chnge

在这篇文章中找到了解决方案,只是很小的改动

Yes, that's right – only change is replacing:

是的,没错——唯一的变化就是取代:

onchange = “this.form.submit();”

onchange = “this.form.submit();”

with:

和:

onchange = “$(this.form).submit();”

onchange = “$(this.form).submit();”