如何在 MVC 3 项目中通过 JsonResult 显示 ModelState 返回的错误?

5

我有一个创建页面,使用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);
                }
            }
        });


    }
1个回答

1

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

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

当出现错误时

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接