【发布时间】:2011-03-17 16:16:37
【问题描述】:
我有一个名为 Domain.Models.BlogPost 的实体,它包含以下属性:
- 邮政编号
- 标题
- 作者
- 发布日期
- 身体
我还有一个名为 Domain.Models.PostComment 的实体,它包含以下属性:
- 评论ID
- 邮政编号
- 作者
- 电子邮件
- 网站
- 身体
BlogPost 包含许多 PostComments。一对多关系。
现在我有这样的视图(通过 html 评论将评论表单与博客文章代码分开):
@model Domain.Models.BlogPost
@using Domain.Models;
@{
ViewBag.Title = "Post";
}
<div class="postTitle">@Model.Title</div>
<div class="subInfo">
Posted by @Model.Author on @Model.PostedDate.ToString("D")
</div>
<div class="postBody">
@Html.Markdown(Model.Body)
</div>
<br />
@Model.PostComments.Count Comment(s).
<div class="comments">
@foreach (PostComment postComment in Model.PostComments)
{
Html.RenderPartial("PostComment", postComment);
}
</div>
<!-- BELOW IS THE ADD COMMENT FORM -->
<div id="addComment">
@using (Html.BeginForm("AddComment", "Blog"))
{
<text>
@Html.Hidden("PostID", Model.PostID)<br />
Name: @Html.TextBox("Author")<br />
Email: @Html.TextBox("Email")<br />
Website: @Html.TextBox("Website")<br />
Body: @Html.TextArea("Body")<br />
<input type="submit" value = "Add Comment" />
</text>
}
</div>
@Html.ActionLink("Add Comment", "AddComment")
问题在于,由于评论表单使用@Html.TextBox("Author") 和@Html.TextBox("Body"),它们填充了来自模型的数据,其中还包含属性Author 和Body。有关如何解决此问题的任何建议,以便在页面加载时这些字段不会获得放入其中的值?
我还尝试创建一个BlogPostViewModel 并将其设置为视图的模型,并将BlogPost 属性分配给我的实际模型:
public class BlogPostViewModel
{
public BlogPost BlogPost { get; set; }
public PostComment NewComment { get; set; }
}
然后我做了@Html.TextBoxFor(x => x.NewComment.Author) 但是当表单发布到这个操作方法时:
public ActionResult AddComment(PostComment postComment)
{
// ...
}
postComment 没有绑定到表单值:/
【问题讨论】:
-
这是默认模型绑定器的一个丑陋事实。我已经打过几次了。我最好的解决方案是将 [Bind(Exclude="Author, Body")] 添加到操作中,然后手动修复问题。我很想听听更好的方法。
-
我也很想听听更好的方法。
-
看到你的更新,尝试基于 NewComment 前缀绑定。即把 [Bind(Prefix = "NewComment")] 放在参数 PostComment postComment 之前
-
我会试试这个,让你知道它是怎么回事。
-
属性“绑定”在此声明类型上无效。它仅对“类,参数”声明有效。 public ActionResult AddComment(PostComment postComment)
标签: c# asp.net-mvc asp.net-mvc-3 razor model-binding