我想将模型从表单传递给控制器,并在同一视图中显示其他模型。我怎样才能做到这一点?我的主要问题是:如何发送到testAcc actionresult,模型CommentModel,并在ViewData["Success"]
中显示文本?
这是我的代码:
@model XYZ.Models._ideaDetailsWrapper
@using XYZ.Tools
<article>
<h2>@Model.idea.Tilte</h2>
<table><tr><td>
<p>
Author: <b>@UserTools.getUser(Model.idea.AuthorID).UserName</b><br />
Add date: @Model.idea.AddDate<br />
Category: @IdeasTools.getCategoryName(Model.idea.CategoryID)<br />
</p></td>
</tr></table>
<p><b>Content:</b><br />
@Model.idea.Content</p>
<br /><br />
// HERE - ADD comment
@using (Html.BeginForm("testAcc", "Ideas", FormMethod.Post))
{
<h4>Add comment:</h4>
@Html.LabelFor(m => m.addComment.Content)
@Html.EditorFor(m => m.addComment.Content)<br />
<input type="submit" value="SendEmails" />
}
@ViewData["Success"]
包装器:
public class _ideaDetailsWrapper
{
public Ideas idea { get; set; }
public IEnumerable<IdeasComment> commentList { get; set; }
public CommentModel addComment { get; set; }
}
行动方法:
[HttpPost]
[Authorize]
public ActionResult testAcc(CommentModel model)
{
CommentModel abs = model;
ViewData["Success"] = "Working!";
// ADD TO DATABASE, but model is null..
return RedirectToAction("Details", "Ideas");
}
答案 0 :(得分:11)
执行此操作的一种方法是使用部分视图。
<强> Details.cshtml 强>
@model XYZ.Models._ideaDetailsWrapper
...
// HERE - ADD Comment
<div id="comment-form">
@Html.Partial("_CommentForm", Model.addComment)
</div>
@Model.message
// add validation javascript to this view
_CommentForm.cshtml (部分视图)
@model XYX.Models.CommentModel
@{
Layout = null;
}
@using (Html.BeginForm("testAcc", "Ideas", FormMethod.Post))
{
@Html.ValidationSummary(true)
<h4>Add comment:</h4>
@Html.LabelFor(m => m.Content)
@Html.EditorFor(m => m.Content)
@Html.ValidationMessageFor(m => m.Content)<br />
<input type="submit" value="SendEmails" />
}
部分视图是强类型的,将提交CommentModel
行动方法:
[HttpPost]
[Authorize]
public ActionResult testAcc(CommentModel model)
{
string abs = model.Content;
TempData["Message"] = "Working!";
// ADD TO DATABASE
return RedirectToAction("Details", "Ideas", new { id = model.Idea.Id });
}
[HttpGet]
[Autorize]
public ActionResult Details(int id)
{
var ideaModel = dbStore.GetIdea(id); // however you do this
var model = new _ideaDetailsWrapper {
idea = ideaModel,
addComment = new CommentModel(),
message = TempData["Message"]
...
};
return View(model);
}
使用TempData
通过重定向传递邮件。在您首次加载页面之前,您将检查TempData["Message"]
操作中是否存在Details
。
修改:对于验证,只需将验证javascript添加到详细信息视图,将ValidationSummary
添加到部分视图。
编辑2:此方法因验证和错误处理而中断。为了实现这一点,它需要AJAX来替换表单div而不重新加载整个页面。
您需要截取普通表单提交并使用AJAX自行处理
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "/Ideas/testAcc",
type: "POST",
data: $("form").serialize()
})
.done(function(partialViewHtml) {
$("#comment-form").html(partialViewHtml);
});
});
您的行动变为
[HttpPost]
public ActioNResult testAcc(CommentModel model)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Details", "Ideas", new { id = model.Idea.Id });
}
return PartialView("_CommentForm", model);
}