如何当的Json返回读取的ModelState错误? [英] How to read modelstate errors when returned by Json?

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

问题描述

我怎么能显示由JSON返回的ModelState错误?

我想要做这样的事情:

 如果(!ValidateLogOn(名称,currentPassword))
    {
        ModelState.AddModelError(_表,用户名或密码不正确。);        //返回一个JSON对象的JavaScript
        返回JSON(新{ModelState中});
    }

什么一定是我的code在视图中读取的ModelState错误,并显示它们?

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

 函数createCategoryComplete(五){
    变种物镜= e.get_object();
    警报(obj.Values​​);
}


解决方案

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

 公众的ActionResult指数()
{
    返回JSON(新
    {
        错误控制=_form
        的errorMessage =用户名或密码不正确。
        someOtherProperty =一些其他的价值
    });
}

How can I display ModelState errors returned by JSON?

I want to do something like this:

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

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

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

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); 
} 

解决方案

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返回读取的ModelState错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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