asp.net-mvc 在 HTML.DropDownList Razor MVC 中处理 onchange 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8973037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:42:08  来源:igfitidea点击:

Handling onchange event in HTML.DropDownList Razor MVC

asp.net-mvcasp.net-mvc-3razorhtml-helper

提问by Milan Mendpara

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

我正在onchange通过简单的 HTML处理具有选定值的事件,如下所示:

<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 onchangewith @Html.DropDownList()

我该如何处理onchange@Html.DropDownList()

回答by dknaack

Description

描述

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

您可以使用该DropDownList方法的另一个重载。选择您需要的一个并传入一个带有您的 html 属性的对象。

Sample

样本

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

More Information

更多信息

回答by pixelfirexy

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

dknaack 的方式对我不起作用,我也找到了这个解决方案:

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