在描述问题时,请多多包涵.
使用局部视图的MVC3应用程序.无法从其父模型的“详细信息”视图中的部分视图中发布“评论”表单.
供参考,ArticleViewModel具有CommentsViewModel的集合,因此存在OTM关系.
详细资料检视
@model ArticleViewModel
// Renders the Article and its Comments - no forms, just display markup
// A nested _Comments partial is used to render the article's comments.
@Html.Partial("_Article", Model)
// Renders HTML and Javascript for the Pagedown editor - POST form inside.
@Html.Partial("_CommentEditor", new CommentViewModel())
@section scripts { /* code here for validation and the javascript editor */ }
_CommentEditor部分视图
@model CommentViewModel
@using (Html.BeginForm("Comment","Article",FormMethod.Post)) {
@Html.TextAreaFor(m => m.Content)
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
}
物品管制员
public ActionResult Details(string slug) {
return View(_articleService.Get(slug));
}
[HttpPost]
public ActionResult Comment(string slug, CommentViewModel comment) {
if(ModelState.IsValid) {
_articleService.AddComment(comment, slug);
}
return RedirectToAction("Details", new { Slug = slug });
}
场景/问题
> / Article / Details / {slug}的Http请求正确呈现了文章,其注释和编辑器表单.
>编辑器按预期工作,但是在单击Submit时,我注意到我的控制器上的Details操作被调用,而不是HttpPost Comment操作.
如您所见,Razor Form帮助器使用POST在Article控制器上指定了Comment操作.
题
为什么会这样呢?我想念什么?
解决方法:
冠军奖!
答案是路由.
与Fiddler往前看,我实际上是向/ article / comment发送POST请求,所以我检查了路由…我怎么错过了这个,我不知道:
routes.MapRoute("Article-Create", "article/create", new { controller = "Article", action = "Create" });
routes.MapRoute("Article-Edit", "article/edit/{slug}", new { controller = "Article", action = "Edit" });
routes.MapRoute("Article-Delete", "article/delete/{slug}", new { controller = "Article", action = "Delete" });
routes.MapRoute("Article", "article/{slug}", new { controller = "Article", action = "Details" });
routes.MapRoute("Articles", "articles", new { controller = "Article", action = "Index" });
评论操作没有明确的路线.在获取文章(article / {slug})时,有一条通俗易懂的REST式路线.因此,在击中默认路由之前,它正在处理Comment POST.
我的特定解决方案(我喜欢显式路由-即使在遇到麻烦时也是如此)是添加一条评论路线,仅适用于所有文章/ {slug}模式:
routes.MapRoute("Article-Comment", "article/comment", new { controller = "Article", action = "Comment" });
问题解决了.不好意思