回发时 MVC ViewModel 集合为空

MVC ViewModel collection null on postback

我有一个 ViewModel,其中包含一个名为 Types 的 SelectListItems 列表。当我进入编辑页面时,类型被填充并且下拉列表包含预期的项目。当我 post 更改回 SelectListItems 列表时为空。即 'model.Types' 为空。

为什么会这样,我该如何解决?

我看到这个问题被问过好几次了,但他们都有不同的答案,我试了几次都没有用。

我是 MVC 的新手,所以请帮忙。

谢谢

我的视图模型:

public class StaticItemViewModel
{
    public Static_Item StaticItem { get; set; }
    public List<SelectListItem> Types { get; set; }     
}

我的控制器:

public class StaticItemController : Controller
{
    private DB db = new DB();

    public ActionResult Edit(int id)
    {            
        Static_Item staticItem = db.Static_Item.Find(id);

        if (staticItem == null)
        {
            return HttpNotFound();
        }

        StaticItemViewModel staticItemViewModel = new StaticItemViewModel()
        {
            StaticItem = staticItem,
            Types = LoadStaticItemTypes(staticItem.Type)
        };

        return View(staticItemViewModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="StaticItem")] StaticItemViewModel model)                    
    {
        if (ModelState.IsValid)
        {
            model.StaticItem.Changed_Date = DateTime.Now;
            db.Entry(model.StaticItem).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(model);
    }

    List<SelectListItem> LoadStaticItemTypes(string selectedType = "")
    {
        List<SelectListItem> items = new List<SelectListItem>();

        foreach (var item in db.Static_Item.Select(s => s.Type).Distinct().OrderBy(s => s))
        {
            items.Add(new SelectListItem { Text = item, Value = item, Selected = item == selectedType });
        }

        return items;
    }
}

我的看法:

@model StaticItemViewModel

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
    {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>@Model.StaticItem.Description</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.StaticItem.UN_Static_Item)

        <div class="form-group">
            @Html.LabelFor(model => model.StaticItem.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StaticItem.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StaticItem.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.StaticItem.Type, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.StaticItem.Type, Model.Types, new { @class="form-control" })
                @Html.ValidationMessageFor(model => model.StaticItem.Type, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

那是因为 Types 只保存选项列表,而实际选项本身永远不会 post 返回。你需要一个 属性 比如:

public List<int> SelectedTypes { get; set; }

然后绑定到您认为的那个:

@Html.ListBoxFor(m => m.SelectedTypes, Model.Types)

假设您的选项值只是类型的 PK,您也可以绑定到 List<string> 等,但它必须是原始类型(字符串、整数等)。您不能 post 支持完整的 Type 对象。如果您需要这些,您将需要使用 ID 列表或其他任何方式从数据库中查找它们。