Aoren Aoren - 24 days ago 5
ASP.NET (C#) Question

Send Dropdownlist helper selected value to POST method

I have this dropdown

new SelectList(ViewBag.ListItems, "pageSize"), "pageSize",
onchange = @"
var form = document.forms[0];

based on the following ViewBag

ViewBag.ListItems = new List<Int16>

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.

public ActionResult Index(int? selectedOption, int? page, string pageSize)

How can I achieve this?


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:

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.

  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(){
        '@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.