Search code examples
asp.net-mvcasp.net-mvc-3razorhtml-helper

Handling onchange event in HTML.DropDownList Razor MVC


I'm handling an onchange event with a selected value by simple HTML like this:

<select onchange="location = this.value;">
         <option value="/product/categoryByPage?PageSize=15" selected="selected">15</option>
         <option value="/product/categoryByPage?PageSize=30" selected="selected">30</option>
         <option value="/product/categoryByPage?PageSize=50" selected="selected">50</option>
</select>

Doing it like this:

List<SelectListItem> items = new List<SelectListItem>();
string[] itemArray = {"15","30","50"};

for (int i = 0; i < itemArray.Count(); i++)
{
    items.Add(new SelectListItem 
    { 
        Text = itemArray[i], 
        Value = "/product/categoryByPage?pageSize=" + itemArray[i]
    });
}

ViewBag.CategoryID = items;
@Html.DropDownList("CategoryID")

How can I handle onchange with @Html.DropDownList()


Solution

  • Description

    You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

    Sample

    @Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
    

    More Information