如何为html设置一个值.下拉列表在asp.net mvc

本文关键字:下拉列表 一个 asp mvc net html 设置 | 更新日期: 2023-09-27 18:14:17

如何为html设置一个值。asp.net MVC中的下拉列表例如,假设我们有这样一个列表

 @Html.DropDownList("Suppliers", Model.PDTO.ProjectSuppliers, new { @class = "text_field multiList hide", @multiple = "multiple" })*@

我知道我可以使用ListBoxFor或者DropDownListFor像这样

@Html.ListBoxFor(model => model.Suppliers, Model.PDTO.ProjectSuppliers, new { @class = "text_field multiList hide", @multiple = "multiple" })

但我想知道我们如何用下拉列表做到这一点,我试图在谷歌搜索,但我发现答案只是为DropDownListFor

请帮忙

如何为html设置一个值.下拉列表在asp.net mvc

DropDownList不是强类型的。要获得DropDownList的选定选项,您应该在您的操作中编写代码。

下面的代码片段可能会对您有所帮助。

在你的动作中:

var selectedValue = new List<int> {1, 2};
ViewBag.ProjectSuppliers= new MultiSelectList(SupplierList, "Id", "SupplierName", selectedValue );

在您的视图:

@Html.DropDownList("Suppliers", (MultiSelectList)ViewBag.ProjectSuppliers, "-----Select-----", new { multiple="" })

不确定这是否是你的意思,但我知道我以前通过加载一个

使用下拉列表
IEnumerable<SelectListItems> selectList
控制器中的

,传递给ViewBag

ViewBag.selectList = selectList;

然后使用

@Html.DropDownList("selectList") 

如果您选择另一条路线,则会有重载。https://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlist (v = vs.118) . aspx

查看下面的ViewBag方法的更详细的示例:http://www.mikesdotnetting.com/article/128/get-the-drop-on-asp-net-mvc-dropdownlists

我们必须将数据从ViewData中分配给下拉列表然后我们将能够将选定值设置为下拉列表,如下所示

private ActionResult GetEmployeesForDropDown()
{
    var lstEmployees = new[] 
    {   
        new Employee { Id = 1, Name = "Emp1" }, 
        new Employee { Id = 2, Name = "Emp2" }, 
        new Employee { Id = 3, Name = "Emp3" } 
    };
    var selectList = new SelectList(lstEmployees, "Id", "Name", 0);  
    //Here 0 is the selectedIndex which we are assigning to dropdownlist, we can pass value we want here to set the index
    ViewData["Employees"] = selectList;  
    // dropdownlist datasource which is a employeelist is assigned to a ViewData here
    return View();
}

视图看起来像这样

@Html.DropDownList("ddEmployees", (SelectList)ViewData["Employees"], "---Select---", new {@class="DropDownCssIfAny"})

控制器:

List<Department> departments = dbHR.Departments.OrderBy(d => d.DEPARTMENT_NAME).ToList();
departmentsList = new SelectList(departments, "DEPARTMENT_ID", "DEPARTMENT_NAME", deptInt);
 ViewBag.DepartmentsList = departmentsList;

视图:

<%: Html.DropDownList("DEPARTMENTS", (IEnumerable<SelectListItem>)ViewBag.DepartmentsList, string.Empty)%>

相关文章: