【问题标题】:Display ModelState error returned by JsonResult in MVC 3 project?在 MVC 3 项目中显示 JsonResult 返回的 ModelState 错误?
【发布时间】:2012-05-04 21:01:59
【问题描述】:

我有一个 create 页面,它使用 JsonResult 操作而不是 ActionResult。在 ActionResult 操作中,错误显示在违规字段旁边的视图上。现在 JsonResult 只返回一个显示在警告框中的字符串。

我可以在视图上显示 ModelState 错误吗?

控制器

[HttpPost]
public JsonResult Create(Tload tload)
    {
        if (ModelState.IsValid)
        {                
          ...save changes
            return Json(new { Success = 1, TransloadID = transload.TransloadID, ex = "" });
        }
        else
        {
        string totalError = "";
        foreach (var obj in ModelState.Values)
        {
            foreach (var error in obj.Errors)
            {
                if (!string.IsNullOrEmpty(error.ErrorMessage))
                {
                    totalError = totalError + error.ErrorMessage + Environment.NewLine;
                }
            }
        } 

        return Json(new { Success = 0, ex = new Exception(totalError).Message.ToString()});
    }

jquery/javascript 代码在视图中

function Save() {
        // Step 1: Read View Data and Create JSON Object
...do stuff here
        // Set 2: Ajax Post
        // Here i have used ajax post for saving/updating information
        $.ajax({
            url: '/Expedite/Create',
            data: JSON.stringify(salesmain),
            type: 'POST',
            contentType: 'application/json;',
            dataType: 'json',
            success: function (result) {

                if (result.Success == "1") {
                    window.location.href = "/Expedite/index";
                }
                else {
                    alert(result.ex);
                }
            }
        });


    }

【问题讨论】:

    标签: json asp.net-mvc-3 error-handling asp.net-mvc-validation


    【解决方案1】:

    为错误设置一个占位符并在最初隐藏它

    <div id="err"></div>
    

    以及何时引发错误

    else {
           $("#err").html(result.ex);
           $("#err").show();
           //or you can use .slideDown() etc            
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-07
      • 1970-01-01
      • 2011-03-09
      • 2013-05-19
      • 2017-11-01
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多