如何在绑定 List 类型时解析 ModelState.IsValid = false?

How do I resolve ModelState.IsValid = false while binding a List type?

我从一个包含 class 对象的列表中得到一个 ModelState.IsValid = false,该对象有自己的 ID。

我看过一些示例,说明如何在绑定时从 [HttpPost] 方法中排除 class 属性,如下所示:

[Bind(Exclude="Id,SomeOtherProperty")]

我的问题:

如何排除属于 属性 的 Id,就像在 List 中一样?或者,如果有更好的方法来处理这个问题,请阐明这个问题。

这是我的 PostController.cs:

 [HttpPost]
 [ValidateAntiForgeryToken]
 [ValidateInput(false)]
 public ActionResult Create([Bind(Include = "Title,URL,IntroText,Body,Created,Modified,Author,Tags")] Post post)
 {
     if (ModelState.IsValid) /*ModelState.IsValid except for its not... */
     { 
           // this is failing so I unwrapped the code below temporarily
     }


         using (UnitOfWork uwork = new UnitOfWork())
         {
             var newPost = new Post
             {
                 Title = post.Title,
                 URL = post.URL,
                 IntroText = post.IntroText,
                 Body = replace,
                 Author = post.Author,
                 Tags = post.Tags

             };

             uwork.PostRepository.Insert(newPost);
             uwork.Commit();
             return RedirectToAction("Index", "Dashboard");
         }


     return RedirectToAction("Index", "Dashboard");
 }

更新:我的Create.cshtml的相关摘录(原来是问题所在。)

<div class="form-group">
     @Html.LabelFor(model => model.Tags, htmlAttributes: new { @class = "control-label col-md-2 col-md-offet-3" })
    <div class="col-md-7">
        @for (var i = 0; i < 4; i++)
        {
            @Html.HiddenFor(m => m.Tags[i].Id)
            @Html.EditorFor(model => model.Tags[i].Name)

        }
    </div>
</div>

要点: Post.cs | Tag.cs

我想包括这张照片,以便您可以直观地看到失败的原因。每个 Tag[i].Id 标签都导致无效状态。

重申一下我的问题,如何从我的 POST 方法中省略 List<Tag> Id 并达到有效状态?

正如 @StephenMuecke 在 OP 的评论中指出的那样。我只需要从视图中删除该字段:

@Html.HiddenFor(m => m.Tags[i].Id)

现在 ModelState.IsValid returns 为真。