Aoren Aoren - 2 months ago 10
ASP.NET (C#) Question

Send Dropdownlist helper selected value to POST method

I have this dropdown

@Html.DropDownList("pageSize",
new SelectList(ViewBag.ListItems, "pageSize"), "pageSize",
new
{
onchange = @"
var form = document.forms[0];
form.action='Home/Index';
form.method='POST';
form.submit();"
})


based on the following ViewBag

ViewBag.ListItems = new List<Int16>
{
5,
20,
50,
100
};


All this placed over a html table in my Home Controller. I want to retrieve the amount of entries the user wants to see in my post method.

[HttpPost]
public ActionResult Index(int? selectedOption, int? page, string pageSize)
{
}


How can I achieve this?

Answer

To start with, pagignation should generally be dealt with via a Get request because of idempotence. Also it will cause fewer issues using the browser back button.

Assuming that your controller could look a little like this:

[HttpGet]
public ActionResult Index(int pageNum = 1, int pageSize = 20)
{
    // Your pagination code here
}

In your view code, you don't need to put inline javascript (tends to be a bad idea anyway) You can put an id and/or a css class on the control to select it.

@Html.DropDownList("pageSize",
  new SelectList(ViewBag.ListItems, "pageSize"), "pageSize",
  new {@id="page-size", @class = "pager-control"})

Then in your javascript you could do something like this:

$(".pager-control").on("change", function(){
    window.location.replace(
        '@Url.Action("Index", "Home")' + '?pageNum=' + $("#page-num").val()
        + '&pageSize=' + $("#page-size").val());
    });

Note that this assumes your page control has an id of "page-num" and a class of "pager-control" as well. You can also choose whether to use replace or href depending on whether you want it in the browser history or not.