我有一個實體,稱爲Domain.Models.BlogPost
其中包含以下屬性:ASP.NET MVC 3模型綁定和表單域
- 帖子ID
- 標題
- 作者
- PostedDate
- 身體
我也有一個實體叫Domain.Models.PostComment
其中包含以下屬性:
- CommentID
- 帖子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
沒有綁定到表單值:/
這是默認模型活頁夾的醜陋事實。我已經打了幾次。我的最佳解決方案是添加[綁定(排除=「作者,身體」)]的行動,然後手動修復snafu。我很樂意聽到更好的方法。 – 2011-03-17 16:21:10
我很樂意聽到更好的方法。 – Chev 2011-03-17 16:24:08
查看您的更新,嘗試基於NewComment前綴進行綁定。即在參數PostComment之前放置[Bind(Prefix =「NewComment」))postComment – 2011-03-17 16:39:10