简体   繁体   English

如何在MVC JsonResult中返回换行符

[英]How to return line breaks in MVC JsonResult

I want to display a javascript alert using the message being passed back from a controller action that returns Json result. 我想使用从返回Json结果的控制器操作传回的消息来显示javascript警报。 I want this message to have line breaks in it. 我希望此消息中包含换行符。

Here is my controller, note the "\\n" to input line breaks: 这是我的控制器,请注意输入换行符的“\\ n”:

[HttpPost]
public JsonResult CreatePO(PONewViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var createPOResult = _managePOsAppServ
            .CreateNewPOHeaderAndDetail(CurrentFacilityId, CurrentUserId, viewModel.VendorId,
                viewModel.CustomerId, viewModel.OrderHeaderId, viewModel.ItemId, viewModel.QtyToOrder,
                viewModel.UnitCost);

        return Json(createPOResult, JsonRequestBehavior.AllowGet);
    }

    var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
    string errorMessage = "";
    if (modelStateErrors.Count() > 0)
    {
        foreach (var error in modelStateErrors)
        {
            errorMessage += error.ErrorMessage + "\n";
        }
    }

    return Json(ActionConfirmation<int>.CreateFailureConfirmation(errorMessage, -1,false).Message, JsonRequestBehavior.AllowGet);
}

However, the \\n is being displayed in the alert box. 但是,\\ n正在警告框中显示。 So it seems the returned Json is escaping the \\n. 所以似乎返回的Json正在逃避\\ n。 How do I get it to be recognized as a line break? 如何将其识别为换行符?

Javascript: 使用Javascript:

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {        
        alert(xhr.responseText);
        hideLoading();
    }
}

How are you alerting the data? 你是如何提醒数据的? Sounds like you're maybe alerting the JSON string, not the JavaScript string. 听起来你可能会警告JSON字符串,而不是JavaScript字符串。 Make sure you parse the JSON in your result by changing alert(xhr.responseText) to alert(jQuery.parseJSON(xhr.responseText)); 确保通过将alert(xhr.responseText)更改为alert(jQuery.parseJSON(xhr.responseText));来解析结果中的JSON alert(jQuery.parseJSON(xhr.responseText));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM