return Json error from ASP.NET MVC

后端 未结 4 1896
悲&欢浪女
悲&欢浪女 2020-12-13 06:11

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:

4条回答
  •  遥遥无期
    2020-12-13 06:56

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

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

    and then at the client side

     .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("
    ")); },

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

提交回复
热议问题