问题是,如何在与模型/数据库绑定的剃刀视图中为dropdownlistfor设置默认值?
型号:
public class Cvm
{
public TCl Cl { get; set; }
public List<Purpose> ListPurpose { get; set; }
控制器:
public ActionResult Create()
{
Cvm cvms = new Cvm();
var purposes = db.Purposes.ToList();
cvms.ListPurpose = purposes;
return View(cvms);
}
查看
@{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var item in Model.ListPurpose)
{
listItems.Add(new SelectListItem
{
Text = item.PurposeDesc
});
}
}
<div class="col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.Clearance.Purpose, htmlAttributes: new { @class = "control-label" })
<br>
@Html.DropDownListFor(model => model.Clearance.Purpose, new SelectList(Model.ListPurpose, "Id", "PurposeDesc"), "Prime Purpose", new { @class = "form-control", Selected = true })
@Html.ValidationMessageFor(model => model.Clearance.Purpose, "", new { @class = "text-danger" })
</div>
</div>
这就是我用数据库中的数据填充下拉列表的方式 现在,在页面加载时,将填充下拉列表,并且该下拉列表的值也为“主要用途”。
保存表单时,目的列中保存在数据库中的内容为NULL 似乎忽略了加载的默认值
答案 0 :(得分:0)
我已经使用
string defaultPupose = "LOCAL EMPLOYMENT";
Selected = item.PurposeDesc == defaultPupose ? true : false
完整代码是
@{
List<SelectListItem> listItems = new List<SelectListItem>();
string defaultPupose = "LOCAL EMPLOYMENT";
foreach (var item in Model.ListPurpose)
{
listItems.Add(new SelectListItem
{
Text = item.PurposeDesc,
Selected = item.PurposeDesc == defaultPupose ? true : false
});
}
}