【问题标题】:MVC: Binding Dropdownlist To Controller and getting Selected index in the controllerMVC:将下拉列表绑定到控制器并在控制器中获取选定索引
【发布时间】:2012-12-14 15:55:29
【问题描述】:

我有一个 MVC# 下拉列表,其中包含模型中定义的值。

@Html.DropDownListFor(model => model.myModel, new SelectList(Model.List, "Value", "Text"))

我希望它像一个按钮一样,即在选择时,在控制器中执行一个动作并返回到同一个视图。我已经为它创建了一个控制器方法,比如

[HttpPost]
public ActionResult Index(int? selectedIndex)
{

}

我想知道如何从视图中获取选定的索引。即,我如何将特定的下拉列表绑定到控制器。

【问题讨论】:

    标签: asp.net-mvc-3 drop-down-menu model controller


    【解决方案1】:

    @Html.DropDownListFor renders an html input tag which won't post to the server when the selection changed.

    您必须使用一些 javascript / jQuery 来捕获下拉列表的更改事件并将值发布到服务器,如下所示:

    $(document).ready(function() {
        $("#myModel").on('change', function(e) {
            $.post('@Url.Action("Index")', {id: $(this).val()}, 
                   function(data) {
                      // here data contains the response from your action index
                   });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多