gpt4 book ai didi

javascript - 确保简单 View 模型对象上的 JSON pretty-print ,从不触及 javascript (ASP.NET MVC 4)

转载 作者:行者123 更新时间:2023-12-02 19:07:31 26 4
gpt4 key购买 nike

我的精神有点脱节。我已经看到如何进行 JSON pretty-print On This Topic使用 JSON.stringify(obj); - 但我有一种情况需要这样做,但 json 从未真正接触过 javascript。它只是 MVC View 模型上的一个字符串。它用于“错误” View ,如下所示...

(我正在使用 jQuery,如果这会打开任何其他选项)

型号

public class FailureViewModel{
public string Name { get; set; }
public string Message { get; set; }
public string JSON { get; set; }
}

它的工作原理是这样的。如果操作失败,则会生成以下 View 。

Controller

        return View("Failure", new FailureViewModel{
Name = "Some Error Name",
Message = "There was an error and the changes were not submitted. Please submit this to the administrator",
JSON = model.ToJson()
});

查看

@model FailureViewModel

@{
ViewBag.Title = "Error With Data Entry";
Layout = "~/Areas/Administrator/Views/Shared/_Layout.cshtml";
}

<article>
<aside class="red">
@Model.Message
</aside>
<aside>
<pre>
@Model.JSON
</pre>
</aside>
</article>

我基本上只是想对 @Model.JSON 进行“字符串化”,这样它就可以很好地显示所有内容并格式化,但我在不真正使 View 变得复杂的情况下很难做到这一点。有什么建议吗?

最佳答案

根据@charlietfl给我的链接,我设计了以下内容来实现我的目标。

查看模型

public class SuccessViewModel {
public string Name { get; set; }
public string Message { get; set; }
public string JSON { get; set; }
}

Controller

    return View("Success", new SuccessViewModel {
Name = "The Title",
Message = "The message",
JSON = model.ToJson()
});

查看

@model SuccessViewModel

@{
ViewBag.Title = "Successful Data Entry";
Layout = "~/Areas/Administrator/Views/Shared/_Layout.cshtml";
}


<article>
<aside class="green">
@Model.Message
</aside>
<aside>
<pre id="json-result">
</pre>
</aside>
</article>

<script type="text/javascript">
$(document).ready(function(){
var str = JSON.stringify(@(new MvcHtmlString(Model.JSON)), undefined, 2); // indentation level = 2
$('#json-result').html(str);
console.log(str);
});
</script>

扩展方法

/// <summary>
/// Allows for any object to be serialized into Json very quickly.
/// </summary>
public static class JsonExtensions {
/// <summary>
/// Serializes an object to Javascript Object Notation.
/// </summary>
/// <param name="item">The item to serialize.</param>
/// <returns>
/// The item serialized as Json.
/// </returns>
public static string ToJson(this object item) {
return Newtonsoft.Json.JsonConvert.SerializeObject(item);
}
}

关于javascript - 确保简单 View 模型对象上的 JSON pretty-print ,从不触及 javascript (ASP.NET MVC 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14185364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com