簡體   English   中英

確保JSON在簡單的View Model對象上打印,從不觸及javascript(ASP.NET MVC 4)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM