簡體   English   中英

如何在asp.net mvc中為html.DropDownList設置值?

[英]how to set a value for the html.DropDownList in asp.net mvc?

例如,如何在asp.net mvc中設置html.dropdownlist的值,假設我們有此列表

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

但是我想知道如何使用DropDownList做到這一點,我試圖在google中搜索,但是找到了僅適用於DropDownListFor答案。

請幫忙。

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

不確定這是否是您的意思,但是我知道我之前已經通過加載下拉列表使用dropdownlist

IEnumerable<SelectListItems> selectList

在控制器中,將其傳遞給ViewBag

ViewBag.selectList = selectList;

然后使用

@Html.DropDownList("selectList") 

在視圖中。

如果您選擇走另一條路線,則會有很多負擔。 https://msdn.microsoft.com/zh-CN/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)%>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM