问题是,如何在razor视图中设置与模型/数据库绑定的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>
这就是我现在用数据库中的数据填充dropdownlistfor的方式,当页面加载时,下拉列表被填充,并且下拉列表的值为“prime purpose”。
当我保存表单时,数据库中保存的内容在purpose列中为空,似乎忽略了加载的默认值
1条答案
按热度按时间eqoofvh91#
我用电脑解决了我的问题
完整代码为