我有一个简单的表单,我通过Create操作向用户展示。在他们提交表单后,我会向他们展示一个新的确认视图,他们可以在其中输入他们的电子邮件地址以发送表单副本。
为了正确填写电子邮件,我需要保留MonthlyReport
他们刚刚填写的表格中的所有数据。但是,我发现很难从 Confirmation 视图中跨 Get 和 Post 请求保留该报告数据。
当我从确认页面发布时,我发现我ConfirmationViewModel
不再包含有效的报告。
[HttpPost]
public ViewResult Create(MonthlyReport model)
{
if (ModelState.IsValid)
{
var modelDto = _factory.CreateDataTransferObject(model);
_repository.Submit(modelDto);
ModelState.Clear();
return Confirmation(model);
}
return Create();
}
[HttpGet]
public ViewResult Confirmation(MonthlyReport model)
{
var confirmation = new ConfirmationViewModel();
confirmation.Report = model;
return View("Confirmation", confirmation);
}
[HttpPost]
public ViewResult Confirmation(ConfirmationViewModel model)
{
if (ModelState.IsValid)
{
try
{
var email = _mailer.MonthlyReportEmail(model);
email.DeliverAsync();
}
catch (Exception error)
{
Trace.WriteLine(String.Format("Sending mail failed: {0}", error));
}
TempData["message"] = "Confirmation e-mail sent.";
}
return View("Confirmation");
}
这是确认视图:
@model Domain.Entities.ConfirmationViewModel
@{
ViewBag.Title = "Confirmation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Monthly report for @Model.Report.LearnerName has been saved.</h2>
@using (Html.BeginForm("Confirmation", "MonthlyReport", Model))
{
<h4>Enter your e-mail address to receive a copy of the report.</h4>
<table>
<tr>
<td colspan="2">@Html.ValidationMessageFor(x => x.EmailAddress)</td>
</tr>
<tr>
<td>@Html.TextBoxFor(x => x.EmailAddress, new { @class = "input-field" })</td>
<td>
<input type="submit" class="small-submit-button" value="Send" />
</td>
</tr>
</table>
}