2014-02-11 73 views
1

我想做cusotm驗證並在驗證失敗的情況下返回false並顯示消息。ValidationMessage和ModelState.AddModelError不起作用

在控制器下面的代碼用於提交發布的數據到數據庫。

 [HttpPost] 
     public JsonResult SubmitDa(IList<AdViewModel> s, String section) 
      { 

      ........... 
       .......... 


      ModelState.AddModelError("MessageError", "Please enter AttendanceDate"); 

      JSONSubmit r = new JSONSubmit(); 
      r.ErrorCount = iError; 
      r.errors = errors; 

      return Json(r, JsonRequestBehavior.AllowGet); 

     } 

下面是在圖文件(CSHTML)

 @Html.ValidationMessage("MessageError") 
     ..... 

     $.AJAX call to `SubmitDa` controller's method. 

消息不是出現在 「MessageError」 確認消息的代碼。請告訴我這裏有什麼問題。

感謝

+1

我認爲這是因爲你返回了r變量的jsonified版本。 ModelState通常會添加到您的響應對象中,但由於您現在只返回json,因此不會將其發送回頁面。 –

+0

Plz建議,我在這種情況下如何處理驗證?基本上,AJAX調用提交數據到服務器,但有幾個驗證,如果它真的只需要完成發佈數據,否則顯示錯誤消息。如何在這裏實現? – dsi

回答

2

如果你要使用錯誤,你真不該發送JSON響應的ModelState。說了這麼多,你可以只在成功的情況下,該控制器具有回JSON處理它,並在頁面處理的響應不同

IE:在頁面像

[HttpPost] 
public ActionResult SubmitDa(IList<AdViewModel> s, String section) 
{ 

     ........... 
      .......... 


     ModelState.AddModelError("MessageError", "Please enter AttendanceDate"); 

     JSONSubmit r = new JSONSubmit(); 
     r.ErrorCount = iError; 
     r.errors = errors; 
     if (r.ErrorCount != 0) 
      return Json(r, JsonRequestBehavior.AllowGet); 

     return View("ViewName", s); // <-- just return the model again to the view, 
            //  complete with modelstate! 
} 

<script> 

$("#buttonId").click({ 
    $.ajax({ 
    type: "POST", 
    url: "PostBackURL", 
    data: $("#formID").serialize(), 
    success: function (response){ 
     //test for a property in the JSON response 
     if(response.ErrorCount && response.ErrorCount == 0) 
     { 
      //success! do whatever else you want with the response 

     } else { 
      //fail - replace the HTML with the returned response HTML. 
      var newDoc = document.open("text/html", "replace"); 
      newDoc.write(response); 
      newDoc.close(); 
     } 

    } 
    }); 
}); 

</script> 
+0

如果返回'View(「ViewName」,s);'s不包含將顯示爲錯誤消息的屬性,它應該工作嗎?我們可以顯示寫在這裏的錯誤信息 - 'ModelState.AddModelError(「MessageError」,「請輸入AttendanceDate」);'在控制器中。視圖應顯示錯誤在 - '@ Html.ValidationMessage(「MessageError」)'。? – dsi

+0

添加驗證摘要('@ Html.ValidationSummary') - 並顯示錯誤。 –

+0

單獨嘗試這兩種 - @ * @ Html.ValidationMessage(「AttendanceDateMessage」)@ Html.ValidationSummary(true)* @。通過ModelState.AddModelError(「MessageError」,「請輸入AttendanceDate」); 或ModelState.AddModelError(String.Empty,「請輸入AttendanceDate」);但它不起作用。 – dsi