【问题标题】:MVC Variable Length Collection Model is NullMVC 可变长度集合模型为 Null
【发布时间】:2018-10-04 05:52:20
【问题描述】:

我有一个用于编辑集合的局部视图(我在这里截断了大部分):

@using CustomSurveyTool.Models
@model Basiclife
<div class="editorRow">
    @using (Html.BeginCollectionItem(""))
    {
        <div class="form-horizontal">
            <div class="row">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <div class="col-md-2">
                    @Html.LabelFor(model => model.Plantype, htmlAttributes: new { @class = "control-label" })

                    @Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Plantype, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-1">
                    <a href="#" class="deleteRow">X</a>
                </div>
            </div>
        </div>
    }
</div>

这是包装视图的一部分:

@using CustomSurveyTool.Models
@model IEnumerable<Basiclife>
@{
    ViewBag.Title = "CreateBasicLifeResponse";
}

<h2>Basic Life Insurance Plans</h2>
<div id="planList">
    @using (Html.BeginForm())
    {
        <div id="editorRows">
            @foreach (var item in Model)
            {
                @Html.Partial("_BasicLifeResponse", item)
                }
        </div>
        @Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", @class = "button" });
        <input type="submit" value="submit" />
    }
</div>

回传到这个控制器:

    [HttpPost]
    public ActionResult CreateBasicLifeResponse(IEnumerable<Basiclife> model)
    {

        foreach(var item in model)
        {
            string currentUserId = User.Identity.GetUserId();
            Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
            int responseid = targetresponse.Id;
            item.ResponseId = responseid;
            db.basiclife.Add(item);
            db.SaveChanges();
        }

        List<Basiclife> basiclife = new List<Basiclife>();
        return View(model);
    }

提交表单后,我在 foreach(var item in model) 上收到 NullReferenceException。这可能是什么原因造成的?

【问题讨论】:

  • 首先使用网络嗅探器(例如 fiddler 或您的浏览器内置的开发者工具)并自己查找发送到服务器的内容。请求正文是有效的表单编码内容吗?重复一个表单很可能会导致具有相同名称的重复字段不会被模型绑定器解析为您所期望的。要么声明一个适合客户端发送的数据的输入模型,要么您最好将表单中的数据收集到一个 json 数组中,该数组将可解析为您当前使用的模型。
  • 您不能使用EditorTemplate 动态添加新的收藏项。一些选项请参考this answer,使用BeginCollectionItem的详细实现请参考this one
  • 我没有看到 MVC5 的示例。 BeginCollectionItem 还能用吗? Github 代码库已经 6 年没有更新了。
  • 我给您的第二个链接包含使用BeginCollectionItem 的示例的完整代码(并且仍然相关)

标签: asp.net-mvc


【解决方案1】:

您需要遵循 MVC 命名约定,该约定涉及在 Razor 视图中使用带索引的 for 循环而不是 foreach。看看这篇文章: How to pass IEnumerable list to controller in MVC including checkbox state?。 我会推荐文章中描述的编辑器模板方法,它与您当前的 PartialView 方法最相似。

【讨论】:

  • 我不明白我的需求与这里的解决方案有何不同:stackoverflow.com/questions/40539321/…
  • 您没有像您引用的解决方案那样使用Html.BeginCollectionElement(),这将是遵守 MVC 命名约定的另一种方式。
  • 我按照上面的链接实现了这个,现在 NullReferenceException 在for(var i=0; i &lt; response.Count; i++)
猜你喜欢
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多