ASP.NET MVC 3模型绑定和表单字段

我有一个名为Domain.Models.BlogPost的实体,它包含以下属性:

  • postID
  • 标题
  • 作者
  • 发表日期
  • 身体

我还有一个名为Domain.Models.PostComment的实体,它包含以下属性:

  • CommentID
  • postID
  • 作者
  • 电子邮件
  • 网站
  • 身体

BlogPost包含许多PostComments 。 一对多的关系。

现在我有这样的观点(通过html评论从博客文章代码中分离出评论表格):

 @model Domain.Models.BlogPost @using Domain.Models; @{ ViewBag.Title = "Post"; } 
@Model.Title
Posted by @Model.Author on @Model.PostedDate.ToString("D")
@Html.Markdown(Model.Body)

@Model.PostComments.Count Comment(s).
@foreach (PostComment postComment in Model.PostComments) { Html.RenderPartial("PostComment", postComment); }
@using (Html.BeginForm("AddComment", "Blog")) { @Html.Hidden("PostID", Model.PostID)
Name: @Html.TextBox("Author")
Email: @Html.TextBox("Email")
Website: @Html.TextBox("Website")
Body: @Html.TextArea("Body")
}
@Html.ActionLink("Add Comment", "AddComment")

问题在于,因为注释表单使用@Html.TextBox("Author")@Html.TextBox("Body") ,所以它们使用模型中的数据填充,其中还包含属性AuthorBody 。 有关如何解决此问题的任何建议,以便这些字段在页面加载时不会获取值?

我还尝试创建一个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没有绑定到表单值:/

您可以将AddComment部分中的字段重命名为不与Model中指定的属性发生冲突的字段,也可以使用Html.TextBox的不同重载覆盖视图中的值Html.TextBox 这个重载采用一个value

value(类型:System.Object)
文本输入元素的值。 如果此值为null,则从ViewDataDictionary对象中检索元素的值。 如果那里不存在值,则从ModelStateDictionary对象检索该值。


更新:由于您添加了“NewComment”作为属性并以这种方式解决了属性命名冲突,所有您需要做的就是将PostComment而不是POST上的整个视图模型绑定到操作,是指示模型绑定器将使用前缀。 这是使用BindAttribute完成的。

 public ActionResult AddComment([Bind(Prefix = "NewComment")] PostComment postComment) 

使用ASP NET MVC模板,以便您可以完全控制填充的内容,并且它是类型安全的。

因此,您将创建一个.ascx模板,该模板采用强类型Comment 。 在你的模型中,你留下一个空的。

TextBox上是否有超载值? 你可以传递string.Empty ……