在MVC中,我尝试将消息重定向到Error页面。错误页面将打开但我没有收到任何错误消息。 这是启动流程的方法。
[HttpPost]
public ActionResult SaveSurvey(vmFollowUpSurvey model)
{
var result = surveyBL.postSurveyResults(model);
if (result != "Record Saved")
{
ModelState.AddModelError(string.Empty, "Survey not saved");
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Error");
return Json(new { Url = redirectUrl });
}
else
{
ModelState.AddModelError(string.Empty, "Survey completed");
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Login");
return Json(new { Url = redirectUrl });
}
}
我的ErrorController然后有一个
的方法 public ActionResult Index()
{
return View();
}
我的视图显示为
<h2>Survey Information Page</h2>
<div>
@using (Html.BeginForm("Index", "Error"))
{
<div class="container">
<div class="row">
@Html.ValidationSummary(false, "", new { @class = "text-info" })
</div>
</div>
}
</div>
那么我怎么做才能让它显示出来呢?
答案 0 :(得分:0)
[HttpPost]
public ActionResult SaveSurvey(vmFollowUpSurvey model)
{
var result = surveyBL.postSurveyResults(model);
if (result != "Record Saved")
{
return RedirectToAction("Index", "Error", new { ErrorMessage= "Survey not saved"} );
}
else
{
ModelState.AddModelError(string.Empty, "Survey completed");
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Login");
return Json(new { Url = redirectUrl });
}
}
--- ErrorModel Class
namespace WebApplication3.Models
{
public class ErrorModel
{
public string ErrorMessage { get; set; }
}
}
--- Error Index.html code
@model WebApplication3.Models.ErrorModel
<h2>Survey Information Page</h2>
<div>
@using (Html.BeginForm("Index", "Error"))
{
<div class="container">
<div class="row">
@Html.ValidationSummary(false, Model.ErrorMessage , new { @class = "text-info" })
</div>
</div>
}
</div>
答案 1 :(得分:0)
您的ErrorController.Index()
方法不了解所使用的模型,因此将消息添加到ModelState
将意味着您的错误页面无法访问它。如果您要重定向到不同的视图,处理此问题的正确方法是将错误放在Session
内。
if (result != "Record Saved")
{
Session["Error"] = "Survey not saved";
...
}
然后在您的错误视图中,您可以执行以下操作:
<h2>Survey Information Page</h2>
<div>
@using (Html.BeginForm("Index", "Error"))
{
<div class="container">
<div class="row">
<span class="error-message">@Session["Error"]</span>
</div>
</div>
}
</div>