ASP.net mvc Call Action on DropDown Value Change

扶醉桌前 提交于 2019-12-03 21:28:52
Darin Dimitrov

You need to use javascript for this. Here's an example. Suppose you have the following view model:

public class MyViewModel
{
    public IEnumerable<SelectListItem> Values { get; set; }
}

which you would populate in your controller:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Values = new[] 
            {
                new Item { Value = "1", Text = "Item 1" },
                new Item { Value = "2", Text = "Item 2" },
                new Item { Value = "3", Text = "Item 3" }
            }
        };
        return View(model);
    }
}

And then the view which is strongly typed to this model:

<%: Html.DropDownListFor(x => x.SelectedValue, 
    new SelectList(Model.Values, "Value", "Text"), 
    new { id = "items" }
)%>

The last part is to register for the change event (using jquery in this example):

$(function () {
    // Register for the change event of the drop down
    $('#items').change(function () {
        // When the value changes, get send an AJAX request to the
        // Filter action passing the selected value and update the
        // contents of some result div with the partial html returned
        // by the controller action
        $('#result').load('<%: Url.Action("filter") %>', 
            { selectedValue: $(this).val() }
        );
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!