1

我有“JsonResult”类型的操作方法。我使用 ajax post 调用它。我想将操作方法​​中的自定义错误返回给 ajax post 并将这些错误显示为验证摘要。

[HttpPost]
public JsonResult RegisterUser(RegistrationModel model)
{
   //if username already exists return custom error to be displayed on view      
   //under validation summary
   // control should go back to error function with message to be displayed.
}


   $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: ko.toJSON(model),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            success(result)
        },
        error: function (req, status, error) {
            error(req, status, error);
        }
    });

  function success(result) {  
    //Do Something
  }

  function error(req, status, error) {
       //Display error messages under validation summary.
  }
4

1 回答 1

4

据我了解,当您发布 ajax 帖子时,它不关心模型验证是否通过,它只关心它是否得到服务器的响应。如果从服务器抛出异常,那么它将命中您的 ajax 错误函数。

所以我要做的是返回一个 json 对象,让我知道验证状态。

if(!ModelState.IsValid){
        var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
        var message = "Please fix the following: " + Environment.NewLine;

        foreach (var modelStateError in modelStateErrors)
        {
            message += modelStateError.ErrorMessage + Environment.NewLine;
        }

     return Json(new {success = false, response = message})
}


 // Do other logic

return Json(new {success = true, response = "Successful message"})

一旦你把这个对象传回来,你可以做下面的 Javascript

success: function (result) {
            if(result.success === true){
                 $('#status-div').empty().html('<div class="success">' + result.response + '</div>');
            }
            if(result.success === false){
                 $('#status-div').empty().html('<div class="fail">' + result.response + '</div>');
            }

        }
于 2013-04-12T23:26:49.820 回答