ASP.NET MVC 3 DropDownList selectedindexchanged

2019-04-29 08:28发布

问题:

I have a piece of functionality that allows users to filter records based on their own status codes. In the menu, I have a custom filters section:

<h3>Custom Filters</h3>
 <br />
   <ul id="ui-ajax-tabs">
      @{ Html.RenderAction("GetGroups", "Manage");}
    </ul>

And my partial view looks like this:

@model IEnumerable<AllEngage.Model.Group>

@using AllEngage.Web.Helpers

@foreach (var group in Model)
{
    <li>
        <label for="@group.GroupName">@group.GroupName</label>
        @Html.DropDownList("GroupItems", group.GroupItems.ToSelectListItems())
    </li>
}

When an item is selected from a dropdownlist, I want an action method to fire in my controller:

[HttpGet]
public ActionResult Index(int page = 1, int groupFilterId = -1)

What would be the best way to go? Fire using json or perform a post back somehow?

回答1:

You need to pass you param to action. The fastes way to do this - pass via query string with the same name as param in action:

http://mysite/GetGroups?groupFilterId=2

To refresh it you need to send ajax request with param whitch will be fired onchange of the dropdown control. Specify some ID for your filter control:

@Html.DropDownList("GroupItems", group.GroupItems.ToSelectListItems(), new {@id="ddlFilter"})

and then using jQuery make a GET request of your data:

$('#ddlFilter').change(function() {
  var queryLink = '@Url.Action("GetGroups")';
  if ($(this).val() != '') {
      queryLink += '?groupFilterId=2';
  }

  $.get(queryLink, function(data) {
      $('#ui-ajax-tabs').html(data);
  });
});   


回答2:

you need to fire ajax call using jquery in click event of dropdown. First chek on click event of dropdown if the value changes then call a jquery ajax call I am pasting the code of jquery .

 $.get("/Wk/Revision/@hTitle/@pageID/?langID=2", function (data) {
                    $("div#dAjaxContent").html(data);
                    $("div#dShow").css("visibility", "visible");
                    $("#dShow").dialog();
                });

// this is for ajax call . the dropdown check do it yourself. "/Wk/Revision/@hTitle/@pageID/?langID=2" this will call the controller method revision . and next i think you will do.



回答3:

I'd recommend doing a post request; you can build one using this:

http://iridescence.no/post/Invoking-ASPNET-MVC-Actions-from-JavaScript-using-jQuery.aspx

You could make an AJAX get request, or if you want to redirect away, you can change the JavaScript's window.location to point to the action you want, as in:

window.location = "/MyController/Index";