2011-05-27 44 views

回答

3

你可以寫一個自定義的行爲過濾:

public class HandleJsonErrors : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var modelState = (filterContext.Controller as Controller).ModelState; 
     if (!modelState.IsValid) 
     { 
      // if the model is not valid prepare some JSON response 
      // including the modelstate errors and cancel the execution 
      // of the action. 
      // TODO: This JSON could be further flattened/simplified 
      var errors = modelState 
       .Where(x => x.Value.Errors.Count > 0) 
       .Select(x => new 
       { 
        x.Key, 
        x.Value.Errors 
       }); 
      filterContext.Result = new JsonResult 
      { 
       Data = new { isvalid = false, errors = errors } 
      }; 
     } 
    } 
} 

,然後付諸行動。

型號:

public class MyViewModel 
{ 
    [StringLength(10, MinimumLength = 5)] 
    public string Foo { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    [HandleJsonErrors] 
    public ActionResult Index(MyViewModel model) 
    { 
     // if you get this far the model was valid => process it 
     // and return some result 
     return Json(new { isvalid = true, success = "ok" }); 
    } 
} 

最後請求:

$.ajax({ 
    url: '@Url.Action("Index")', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    data: JSON.stringify({ 
     foo: 'abc' 
    }), 
    success: function (result) { 
     if (!result.isvalid) { 
      alert(result.errors[0].Errors[0].ErrorMessage); 
     } else { 
      alert(result.success); 
     } 
    } 
}); 
+0

嘿達林...偉大的答案。我準備在這裏採取行動。你今天還會推薦這種方法,ASP.NET MVC 4和5出門嗎? – 2013-08-22 15:14:21

+0

我認爲你提供的這個答案是一個更好的方法:http://stackoverflow.com/a/7287646/114029 – 2013-08-22 15:49:46

1

像這樣?

$.ajax({ 
        type: "POST", 
        url: $('#dialogform form').attr("action"), 
        data: $('#dialogform form').serialize(), 
        success: function (data) { 
         if(data.Success){ 
          log.info("Successfully saved"); 
          window.close(); 
         } 
         else { 
          log.error("Save failed"); 
          alert(data.ErrorMessage); 
        }, 
        error: function(data){ 
         alert("Error"); 
        } 
       }); 


    [HttpPost] 
    public JsonResult SaveServiceReport(Model model) 
    { 
     try 
     { 
      // 
     } 
     catch(Exception ex) 
     { 
      return Json(new AdminResponse { Success = false, ErrorMessage = "Failed" }, JsonRequestBehavior.AllowGet); 
     }