下面是我在视图中的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值到“活动”或“非活动”,下拉列表已经是这两个值。从我的数据库中我在ViewBag.IsStatus
中分配值。
现在假设我的值是来自DB的“InAactive”,然后如何在Dropdown中将其指定为Selected值,而不是默认情况下将First下拉显示为选中。
答案 0 :(得分:1)
如果使用MVC,最好使用DropDownListFor
。但是对于您的情况,只需创建SelectList
并将其传递给DropDownList
。 SelectList
contructor对所选值具有重载:
@{ //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>
答案 1 :(得分:1)
如果您的模型具有Status属性,则只需将该值赋给该属性(例如在控制器中):
模型
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" })