在进行jquery ajax发布时,如何从我的asp.net mvc控制器返回错误?

时间:2022-10-17 11:15:26

I'm creating a website in ASP.NET MVC and have stumbled across something I really can't figure out.

我正在ASP.NET MVC中创建一个网站,偶然发现了一些我真想不通的东西。

I've got a user profile page that allows a user to change his password. On the serverside, I want to validate that the user has entered a correct "current" password before allowing the change.

我有一个用户个人资料页面,允许用户更改他的密码。在服务器端,我想验证用户是否在允许更改之前输入了正确的“当前”密码。

What's the best way to return to my View when the password isn't correct? I've tried using ModelState.AddModelError and then return Json(View()) but I can't see the error message anywhere in the JSON object returned to the browser.

当密码不正确时,返回我的View的最佳方法是什么?我已经尝试使用ModelState.AddModelError然后返回Json(View())但我无法在返回浏览器的JSON对象中的任何位置看到错误消息。

What's the best way to do this using jquery on the client?

在客户端使用jquery执行此操作的最佳方法是什么?

/Jesper

2 个解决方案

#1


I would create to classes

我会创建课程

JsonOK : JsonResult { ... }
JsonError : JsonResult { ... }

And use those 2 for OK and Error responses.

并将这些2用于确定和错误响应。

try
{
    ...
}
catch (Exception ex)
{
    return JsonError(ex.Message);
    // or output your own message
    // or pass into it ModelState with your errors
}

#2


ModelState does not automatically do anything with the returned Json. You should manually fill in a model object with data you want to return to the client.

ModelState不会自动对返回的Json执行任何操作。您应该使用要返回到客户端的数据手动填写模型对象。

Alternatively, if you want to report errors to the client, you can throw an exception in the controller action method and handle it in jQuery.

或者,如果要向客户端报告错误,可以在控制器操作方法中抛出异常并在jQuery中处理它。

#1


I would create to classes

我会创建课程

JsonOK : JsonResult { ... }
JsonError : JsonResult { ... }

And use those 2 for OK and Error responses.

并将这些2用于确定和错误响应。

try
{
    ...
}
catch (Exception ex)
{
    return JsonError(ex.Message);
    // or output your own message
    // or pass into it ModelState with your errors
}

#2


ModelState does not automatically do anything with the returned Json. You should manually fill in a model object with data you want to return to the client.

ModelState不会自动对返回的Json执行任何操作。您应该使用要返回到客户端的数据手动填写模型对象。

Alternatively, if you want to report errors to the client, you can throw an exception in the controller action method and handle it in jQuery.

或者,如果要向客户端报告错误,可以在控制器操作方法中抛出异常并在jQuery中处理它。