Handling onchange event in HTML.DropDownList Razor MVC

133,794

Solution 1

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

Solution 2

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
Share:
133,794
Milan Mendpara
Author by

Milan Mendpara

A die hard OwlCity fan who also loves programming, photography and oil painting. It's always great to be a part of stack community. Catch me on appledelegate [at] yahoo [dot] com

Updated on March 18, 2020

Comments

  • Milan Mendpara
    Milan Mendpara about 4 years

    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()

  • AZ_
    AZ_ over 7 years
    How to use location?
  • Alan Baljeu
    Alan Baljeu over 4 years
    @razor-code WHERE @ razor-code. What does this even mean? Where/why do I put two drop-down lists?