2014-01-23 128 views
2

我想在ajax提交返回錯誤後出現錯誤。我不確定我錯過了什麼,但我無法讓它工作。這個問題基本上是一樣的 - ModelState.AddModelError is not being displayed inside my view但我仍然沒有任何運氣。我對Ajax和MVC(任何版本)的使用經驗仍然有限。這是一個非常簡單的例子,其中大部分是我從前面的鏈接中獲得的。MVC 4 Ajax.BeginForm和ModelState.AddModelError

查看:test.cshtml

@model TestProject.VisitLabResult 

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js") 
@Scripts.Render("~/Scripts/ckeditor/ckeditor.js") 

@{ 
    AjaxOptions ajaxOpts = new AjaxOptions 
    { 
     Url = Url.Action("test"), 
     HttpMethod = "Post", 
     LoadingElementId = "loading", 
     LoadingElementDuration = 500, 
     OnSuccess = "processData" 
    }; 
} 
@Html.ValidationMessage("CustomError") 


<div id="loading" class="load" style="display:none"> 
    <p>Saving...</p> 
</div> 

<table> 
@for (int item = 0; item < 10; item++) 
{ 
    <tr id = @item> 
    @using (Ajax.BeginForm(ajaxOpts)) 
    { 
     @Html.ValidationSummary(true) 

     @Html.AntiForgeryToken() 

     <td> 
      <input type="submit" value="Create" /> 
     </td> 

     <td id = @(item.ToString() + "td")> 
     </td> 
    } 
    </tr> 
    } 
</table> 

控制器:HomeController.cs

public ActionResult test() 
{ 
    return View(); 
} 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult test(VisitLabResult vlr, int visitid = 28) 
{ 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      if (Request.IsAjaxRequest()) 
      { 
       throw new Exception("error"); 
      } 
      else 
       return View(vlr); 
     } 
     else 
      return View(vlr); 
    } 
    catch (Exception ex) 
    { 
     ModelState.AddModelError("CustomError", "The Same test Type might have been already created, go back to the Visit page to see the available Lab Tests"); 
     return View(vlr); 
    } 
} 

型號

public class VisitLabResult 
{ 
    public int visitid { get; set; } 
} 

如果一個Ajax請求我拋出一個錯誤,它的捕獲和一個錯誤被添加到ModelState中。儘管這個錯誤從未出現在頁面上。我是否以正確的方式接近這一切?或者我需要採取不同的路線?我感謝任何幫助。

+0

發現這個(http://stackoverflow.com/a/7329127/978528)更多的搜索後,似乎做我所需要的。 – nickfinity

回答

0

只是爲了澄清其他人打這個問題的解決方案。阿賈克斯幫手火災OnSuccess VS OnFailure基於每AjaxOptions docs返回的HTTP代碼:

OnSuccess:如果響應狀態是在200系列調用此函數。
OnFailure:如果在200範圍內的響應狀態不是,則會調用此函數。

換句話說,你必須手動指定,通過改變Response.StatusCode回你的ActionResult時,然後再返回你在你的OnFailure js的方法期待的任何值出現了故障。你可以開車,基於你想要的任何業務邏輯(即catch Exception ex)!ModelState.IsValid ...)

[HttpPost] 
public ActionResult Search(Person model) 
{ 
    if (ModelState.IsValid) { 
    // if valid, return a HTML view inserted by AJAX helper 
    var results = PersonRepository.Get(model) 
    return PartialView("Resulsts", vm); 

    } else { 
    // if invalid, return a JSON object and handle with OnFailure method 
    Response.StatusCode = (int)HttpStatusCode.BadRequest; 
    return Json(new { errors = ModelState.Values.SelectMany(v => v.Errors) }); 

    } 
} 

進一步閱讀

相關問題