web-dev-qa-db-fra.com

Gestion de l'événement onchange dans HTML.DropDownList Razor MVC

Je gère un événement onchange avec une valeur sélectionnée par simple HTML comme ceci:

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

Faire comme ça:

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

Comment puis-je gérer onchange avec @Html.DropDownList()

32
Milan Mendpara

La description

Vous pouvez utiliser une autre surcharge de la méthode DropDownList. Choisissez celui dont vous avez besoin et passez un objet avec vos attributs html.

Échantillon

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

Plus d'information

58
dknaack

La voie de dknaack ne fonctionne pas pour moi, j'ai aussi trouvé cette solution:

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

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

Dans le contrôleur, vous pouvez ajouter:

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

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
5
pixelfirexy