Invoking particular action on dropdown list selection in MVC

后端 未结 7 1777
时光取名叫无心
时光取名叫无心 2021-02-01 18:08

I have a dropdown list in an MVC view. On selection change of dropdown list I want to call specific action method in the controller.

What I have done on view is this :

7条回答
  •  再見小時候
    2021-02-01 19:05

    From the controller action, you're going to make the call the same way:

    <%= Html.DropDownList(ddl, ViewData["items"] as SelectList, new { onchange = string.format("doSomething({0}); return false;", action) }) %>
    

    Once you do that, put a Javascript function on your page that calls the method. How you call it, however, is going to depend on whether it's an AJAX call or not. That is, whether you want a page round-trip or not. For the non-AJAX call:

    function doSomething(action) {
        window.location.href = action;
    }
    

    If it's an AJAX call:

    function doSomething(action) {
        $.load(action);
    }
    

    To pass parameters to the action, you just need to make sure that all of the data elements you want to pass are contained within the

    tag. For example, let's say you want to include a first and last name with your drop down list. In the view, you'll do something like this:

    <%= using (Html.BeginForm()) 
       { %>
        
    First Name: <%= Html.TextBox("FirstName") %>
    Last Name: <%= Html.TextBox("LastName") %>
    Assign to: <%= Html.DropDownList(ddl, ViewData["items"] as SelectList, new { onchange = string.format("doSomething({0}); return false;", ViewData["action"]) }) %>
    <% } %>

    In the Javascript function:

    function doSomething(action) {
        var firstName = $('#FirstName').val();
        var lastName = $('#LastName').val();
        $.load(action, { first: firstName, last: lastName });
    }
    

提交回复
热议问题