One way to do this is to use a Partial View.
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 (Partial View)
@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" />
}
The partial view is strongly typed and will submit the CommentModel
Action methods:
[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);
}
Use TempData
to pass the message through redirect. You'll check if TempData["Message"]
exists in the Details
action when you first load the page directly before you use it.
Edit: For Validation just add the validation javascript to the Details view and the ValidationSummary
to the partial view.
Edit 2: This method breaks down with validation and error handling. For this to work it needs AJAX to replace the form div without reloading the entire page.
You need to intercept the normal form submission and handle it yourself using AJAX
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "/Ideas/testAcc",
type: "POST",
data: $("form").serialize()
})
.done(function(partialViewHtml) {
$("#comment-form").html(partialViewHtml);
});
});
Your action becomes
[HttpPost]
public ActioNResult testAcc(CommentModel model)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Details", "Ideas", new { id = model.Idea.Id });
}
return PartialView("_CommentForm", model);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…