2017-01-16 92 views
0

在MVC中,我試圖將消息重定向到錯誤頁面時。錯誤頁面將打開,但我不會收到錯誤消息。 這是啓動過程的方法。MVC重定向到錯誤頁面不顯示消息

 [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

你是不是裏面JSON返回錯誤? –

+0

你有沒有想法或我應該幫你重寫代碼。 –

+0

不知道我明白我認爲Validationsummary會處理那 –

回答

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> 
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> 
相關問題