I have a view with model BlogPostViewModel:
public class BlogPostViewModel
{
public BlogPost BlogPost { get; set; }
public PostComment NewComment { get; set; }
}
This view is rendered when action method BlogPost is hit. The view displays information regarding the blog post as well as a list of comments on the blog post by iterating over Model.BlogPost.PostComments. Below that I have a form allowing users to post a new comment. This form posts to a different action AddComment.
[HttpPost]
public ActionResult AddComment([Bind(Prefix = "NewComment")] PostComment postComment)
{
postComment.Body = Server.HtmlEncode(postComment.Body);
postComment.PostedDate = DateTime.Now;
postCommentRepo.AddPostComment(postComment);
postCommentRepo.SaveChanges();
return RedirectToAction("BlogPost", new { Id = postComment.PostID });
}
My problem is with validation. How do I validate this form? The model of the view was actually BlogPostViewModel. I’m new to validation and am confused. The form uses the strongly-typed helpers to bind to the NewComment property of BlogPostViewModel and I included the validation helpers as well.
@using (Html.BeginForm("AddComment", "Blog")
{
<div class="formTitle">Add Comment</div>
<div>
@Html.HiddenFor(x => x.NewComment.PostID) @* This property is populated in the action method for the page. *@
<table>
<tr>
<td>
Name:
</td>
<td>
@Html.TextBoxFor(x => x.NewComment.Author)
</td>
<td>
@Html.ValidationMessageFor(x => x.NewComment.Author)
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
@Html.TextBoxFor(x => x.NewComment.Email)
</td>
<td>
@Html.ValidationMessageFor(x => x.NewComment.Email)
</td>
</tr>
<tr>
<td>
Website:
</td>
<td>
@Html.TextBoxFor(x => x.NewComment.Website)
</td>
<td>
@Html.ValidationMessageFor(x => x.NewComment.Website)
</td>
</tr>
<tr>
<td>
Body:
</td>
<td>
@Html.TextAreaFor(x => x.NewComment.Body)
</td>
<td>
@Html.ValidationMessageFor(x => x.NewComment.Body)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="Add Comment" />
</td>
</tr>
</table>
</div>
}
How in the AddComment action method do I implement validation? When I detect Model.IsValid == false then what? What do I return? This action method is only binding to the PostComment property of the pages initial BlogPostViewModel object because I don’t care about any other properties on that model.
You need to repopulate the model and send to view. However, you don’t need to do this by hand, you can use action filters.
see:
http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg
Specifically:
Usage: