У меня есть представление с моделью BlogPostViewModel
:
public class BlogPostViewModel
{
public BlogPost BlogPost { get; set; }
public PostComment NewComment { get; set; }
}
Это представление отображается при выборе метода действия BlogPost
. В представлении отображается информация о сообщении в блоге, а также список комментариев к сообщению в блоге путем повторения Model.BlogPost.PostComments
. Ниже у меня есть форма, позволяющая пользователям оставлять новые комментарии. Эта форма публикуется в другом действии 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 });
}
Моя проблема с проверкой. Как проверить эту форму? Модель вида на самом деле была BlogPostViewModel
. Я новичок в проверке и запутался. Форма использует строго типизированные помощники для привязки к свойству NewComment
элемента BlogPostViewModel
, и я также включил помощники проверки.
@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>
}
Как в методе действия AddComment
реализовать проверку? Когда я обнаружу Model.IsValid == false
, что тогда? Что мне вернуть? Этот метод действия привязывается только к свойству PostComment
начального объекта BlogPostViewModel
страницы, потому что мне не нужны никакие другие свойства этой модели.