模板视图模型';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都具有falseSelected属性值。然后呈现我的视图:

@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被预先选中。预期的行为是有一个未选择的下拉列表。有人能帮忙吗?

模板视图模型';s SelectList属性在视图中呈现时被神奇地选中

最终我找到了一个解决方案。将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" })