从ASP.NET MVC返回JSON错误 [英] return Json error from ASP.NET MVC

查看:286
本文介绍了从ASP.NET MVC返回JSON错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过JSON从ASP.NET MVC控制器返回一个错误消息。我想在屏幕上显示回车,这样的错误看起来像:

I'm trying to return an error message via Json from ASP.NET MVC controller. I want to display carriage returns on the screen, so the error will look like:

错误1

  错误2。

Error 1.
Error 2.

而不是ERROR1。\\ u003cbr / \\ u003eErro2。\\ u003cbr \\ u003e

下面是我的ASP.NET MVC code

Here's my ASP.NET MVC code

Response.StatusCode = (int)HttpStatusCode.BadRequest;
string str = "Error 1.<br/>Error 2.<br.>";
return Json(str);

JavaScript的(节录):

JavaScript (redacted):

.ajax({...
     error: function(xhr, textStatus, exceptionThrown) {
        $('#result').html(xhr.responseText);
     },

调试xhr.responseText收益率:。ERROR1 \\ u003cbr / \\ u003eErro2 \\ u003cbr \\ u003e

任何想法?

推荐答案

会更好在客户端返回的错误列表,然后生成HTML。

would be nicer to return a list of errors and then build the html at the client.

Response.StatusCode = (int)HttpStatusCode.BadRequest;
List<string> errors = new List<string>();
//..some processing
errors.Add("Error 1");
//..some processing
errors.Add("Error 2");
return Json(errors);

和然后在客户端

 .ajax({...
    error: function(xhr, textStatus, exceptionThrown) {
      var errorData = $.parseJSON(xhr.responseText);
      var errorMessages = [];
      //this ugly loop is because List<> is serialized to an object instead of an array
      for (var key in errorData)
      {
         errorMessages.push(errorData[key]);
      }
       $('#result').html(errorMessages.join("<br />"));
  },

您也可以返回一个更具体的错误对象,并使用模板解决方案,但这个想法

you can also return a more specific error object and use a template solution, but this is the idea

这篇关于从ASP.NET MVC返回JSON错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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