如何在 MVC 的 DropDownList 中显示选定的值

How to show selected value in DropDownList of MVC

下面是我的 DropDownList 视图

<div class="col-xs-8 col-sm-8 col-md-4">                           
 @Html.DropDownList("Status",new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { @class = "form-control" })
</div> 

来自 DB 的值可以是 "Active" 或 "Inactive" 并且下拉菜单已经有这两个值。从我的数据库中,我在 ViewBag.IsStatus 中赋值。 现在假设我的值来自数据库 "InAactive" 那么如何将其分配为下拉列表中的选定值而不是默认显示第一个下拉列表作为选定值。

如果您使用 MVC,最好使用 DropDownListFor。但对于您的情况,只需创建 SelectList 并将其传递给 DropDownListSelectList 构造函数对所选值有重载:

@{ //theese lines actually should be in controller.
 var list = new List<SelectListItem> 
             { 
             new SelectListItem 
                   { 
                       Text="Active", 
                       Value = "0" 
                   }
             ,new SelectListItem
                   { 
                       Text="InActive", 
                       Value = "1" 
                    }
             }
}

//thats your code
<div class="col-xs-8 col-sm-8 col-md-4">                           
   @Html.DropDownList("Status",new SelectList(list, "Value", "Text", ViewBag.IsStatus), new { @class = "form-control" })
</div> 

如果您有一个状态为 属性 的模型,那么只需将此值分配给 属性(例如在控制器中):

型号

public class Model
{

    public string Status {get;set;}
} 

控制器

public ActionResult SomeAction()
{
    //the value has to correspond to the Value property of SelectListItems
    //that you use when you create dropdown
    //so if you have new SelectListItem{ Text="Active", Value = "Active" }
    //then the value of Status property should be 'Active' and not a 0
    var model = new Model{Status = "Active"}

    return this.View(model);
}

查看:

@model Model


@Html.DropDownListFor(m=>m.Status,new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { @class = "form-control" })