[英]Ensuring JSON pretty print on simple View Model object that never touches javascript (ASP.NET MVC 4)
我有一點心理上的脫節。 我已經看過如何使用JSON.stringify(obj);
在這個主題上做JSON漂亮打印JSON.stringify(obj);
- 但我有一種情況需要這樣做,但json從未真正接觸過javascript。 它只是MVC視圖模型上的一個字符串。 這是一個“錯誤”視圖,像這樣......
(我正在使用jQuery,如果它打開任何其他選項)
public class FailureViewModel{
public string Name { get; set; }
public string Message { get; set; }
public string JSON { get; set; }
}
它有點像這樣。 如果操作失敗,則會生成以下視圖。
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
進行“stringify”,所以它顯示了所有的好和格式化,但我在沒有真正卷積視圖的情況下無法做到這一點。 有什么建議么?
從@ charlietfl
給我的鏈接中,我設計了以下內容來實現我的目標。
public class SuccessViewModel {
public string Name { get; set; }
public string Message { get; set; }
public string JSON { get; set; }
}
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.