从ASP.NET MVC返回Json错误

Dea*_*ean 40 asp.net-mvc jquery

我试图从ASP.NET MVC控制器通过Json返回一条错误消息.我想在屏幕上显示回车符,因此错误将如下所示:

错误1.
错误2.

代替 "Error1.\u003cbr/\u003eErro2.\u003cbr.\u003e"

这是我的ASP.NET MVC代码

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

JavaScript(编辑):

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

调试xhr.responseText会产生: ""Error1.\u003cbr/\u003eErro2.\u003cbr.\u003e""

有任何想法吗?

Avi*_*nto 72

会更好地返回错误列表,然后在客户端构建html.

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);
Run Code Online (Sandbox Code Playgroud)

然后在客户端

 .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 />"));
  },
Run Code Online (Sandbox Code Playgroud)

您还可以返回更具体的错误对象并使用模板解决方案,但这是个主意


Hec*_*rea 14

如果您使用的是JSON,那么您可能不希望嵌入HTML(这样就会失去返回您将在视图上格式化的"数据"对象的目的.)

如果要返回HTML,可以在控制器中执行此操作:

Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Content("Error 1.<br/>Error 2.<br/>"); 
Run Code Online (Sandbox Code Playgroud)


Ole*_*leg 5

在我看来,你已经几乎把一切都做对了.您在其中的结果xhr.responseText是一个JSON字符串.所以你应该只插入一个额外的JSON.parse函数调用

.ajax({...
    error: function(xhr, textStatus, exceptionThrown) {
        $('#result').html(JSON.parse(xhr.responseText));
    },
Run Code Online (Sandbox Code Playgroud)

然后数据'"Error1.\u003cbr/\u003eErro2.\u003cbr.\u003e"'将转换为字符串'Error 1.<br/>Error 2.<br/>'.

success事件处理程序内部ajax函数JSON.parse为您调用,但它不在error处理程序内部执行此操作.因此,您必须手动执行从JSON字符串转换服务器响应.