gpt4 book ai didi

javascript - json stringify 不能在 asp.net mvc 页面上工作

转载 作者:行者123 更新时间:2023-11-29 15:34:52 25 4
gpt4 key购买 nike

我有这个结果

http://screencast.com/t/s1loWQQ6wZG

https://content.screencast.com/users/levalencia/folders/Jing/media/8c8f0201-4a75-4f91-b311-6ed64c382fac/2015-05-22_1932.png

我的代码如下:

为了美化 JSON,我缺少什么?

查看

@model PruebasAD.Models.SuccessViewModel
@{
ViewBag.Title = "TestRestCall";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>TestRestCall</h2>
<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>

Controller Action

public async Task<ActionResult> TestRestCall()
{
Uri serviceRoot = new Uri(azureAdGraphApiEndPoint);
var token = await GetAppTokenAsync();
string requestUrl = "https://graph.windows.net/mysaasapp.onmicrosoft.com/users?api-version=2013-04-05";

HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", token);

HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl));

if (hrm.IsSuccessStatusCode)
{
string jsonresult = await hrm.Content.ReadAsStringAsync();
return View("TestRestCall", new SuccessViewModel
{
Name = "The Title",
Message = "The message",
JSON = jsonresult.ToJson()
});
}
else
{
return View();
}

}

和模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PruebasAD.Models
{
public class SuccessViewModel
{
public string Name { get; set; }
public string Message { get; set; }
public string JSON { get; set; }
}
}

最佳答案

首先您需要使用 JSON.parse 将模型转换为 javascript 对象,然后传递给 JSON.stringify

请参阅 json.parse 的文档

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

关于javascript - json stringify 不能在 asp.net mvc 页面上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418619/

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