ASP.net mvc Call Action on DropDown Value Change

ε祈祈猫儿з 提交于 2019-12-05 06:41:34

问题


Ive got a dropdown on one of my views. This dropdown only has for entries. Basically i need to know how to call an action when the dropdown value is changed?

My situation is: Im making a simple inbox page. The dropdown has the filter options: View All, View Invites, View Replies etc..

When the user selects a filter option from the dropdown I want to call to an action to return the new view with the filtered data.

Any ideas? Im guessing it is somehow going to be a script attached to the OnChange of the dropdown, but i wouldnt have a clue what the syntax is or how call MVC action from the script.

Thanks in advance


回答1:


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() }
        );
    });
});


来源:https://stackoverflow.com/questions/3920666/asp-net-mvc-call-action-on-dropdown-value-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!