模板视图模型';s SelectList属性在视图中呈现时被神奇地选中
本文关键字:视图 神奇 属性 模型 SelectList | 更新日期: 2023-09-27 18:30:01
我有一个主细节视图,允许用户通过jQuery DOM操纵0动态添加子记录,然后将整个主细节表单发布回我的HttpPost
Edit
方法。我的主视图模型是这样的:
public class FooViewModel
{
// Other properties skipped for brevity
public ICollection<BarViewModel> Bars { get; set; }
}
我的儿童视图模型:
public class BarViewModel
{
public int BazId { get; set; }
public IEnumerable<SelectListItem> BazSelectList { get; set; }
}
在我的Edit
操作中,我通过实体框架和自动映射程序填充视图模型:
public class FooController : Controller
{
public ActionResult Edit(int id)
{
// Fetch from db through Entity Framework,
// project to view model through AutoMapper
var viewModel = FooRepository.GetById(id)
.Project()
.To<FooViewModel>()
.Single();
// Populate ViewBag with an empty template BarViewModel to be manipulated
// through jQuery
ViewBag.BarTemplateViewModel = new BarViewModel
{
BazSelectList = FooRepository.GetBazSelectList()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(FooViewModel viewModel)
{
// Skipped for brevity
}
}
在调试器中,我确保当向我的Edit
操作方法触发GET请求时,BazSelectList
中的所有SelectListItem
都具有false
的Selected
属性值。然后呈现我的视图:
@model FooViewModel
@using (Html.BeginForm())
{
@*Other properties skipped for brevity*@
@*Model binding magic here, editor template rendered for each BarViewModel*@
@Html.EditorFor(m => m.Bars)
<button type="button" class="btn btn-default">Add Bar</button>
}
@* BarViewModel template here *@
@Html.Partial("EditorTemplates/BarViewModel",
(BarViewModel)ViewBag.BarTemplateViewModel)
我的BarViewModel
编辑器模板:
@model BarViewModel
<div class="form-group">
@Html.LabelFor(m => m.BazId, new { @class = "col-md-5 control-label" })
<div class="col-sm-6">
@Html.DropDownListFor(m => m.BazId,
Model.BazSelectList,
string.Empty,
new { @class = "form-control" })
</div>
</div>
当视图渲染时,ViewBag.BarTemplateViewModel.BazSelectList
在不应该选择的时候选择了一个SelectListItem
,因为我正在向ViewBag
传递一个空的BarViewModel
实例。这一点得到了确认,因为当我点击"添加栏"按钮时,我可以看到BazSelectList
被预先选中。预期的行为是有一个未选择的下拉列表。有人能帮忙吗?
最终我找到了一个解决方案。将IEnumerable<SelectListItem>
封装为对SelectList
构造函数的调用解决了我的问题,即更改以下内容:
@Html.DropDownListFor(m => m.BazId,
Model.BazSelectList,
string.Empty,
new { @class = "form-control" })
至
@Html.DropDownListFor(m => m.BazId,
new SelectList(Model.BazSelectList, "Value", "Text"),
string.Empty,
new { @class = "form-control" })