Json 返回时如何读取模型状态错误? [英] How to read modelstate errors when returned by Json?

查看:14
本文介绍了Json 返回时如何读取模型状态错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示 JSON 返回的 ModelState 错误?

How can I display ModelState errors returned by JSON?

我想做这样的事情:

 if (!ValidateLogOn(Name, currentPassword))
    {
        ModelState.AddModelError("_FORM", "Username or password is incorrect.");

        //Return a json object to the javascript
        return Json(new { ModelState });
    }

视图中的代码必须是什么才能读取 ModelState 错误并显示它们?

What must be my code in the view to read the ModelState errors and display them?

我在视图中读取 JSON 值的实际代码如下:

My actual code in the view to read the JSON values is as follows:

function createCategoryComplete(e) { 
    var obj = e.get_object(); 
    alert(obj.Values); 
} 

推荐答案

如果返回 JSON,则不能使用 ModelState.视图需要的一切都应该包含在 JSON 字符串中.因此,您可以将错误添加到您正在序列化的模型中,而不是将错误添加到 ModelState 中:

If you are returning JSON, you cannot use ModelState. Everything that the view needs should be contained inside the JSON string. So instead of adding the error to the ModelState you could add it to the model you are serializing:

public ActionResult Index()
{
    return Json(new 
    {
        errorControl = "_FORM",
        errorMessage = "Username or password is incorrect.",
        someOtherProperty = "some other value"
    });
}

这篇关于Json 返回时如何读取模型状态错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆