【问题标题】:c# to json not rendering properly in viewc# to json 在视图中没有正确呈现
【发布时间】:2011-01-05 14:57:17
【问题描述】:

嗨,我正在尝试将字符串发送到看起来像 json 的视图。

我正在发送地点列表:

class Place 
        {
            public string title { get; set; }
            public string description { get; set; }
            public double latitude { get; set; }
            public double longitude { get; set; }
        }

List<Place> placeList = new List<Place>(); 
//add places to PlaceList

//Then i do this
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string sJSON = oSerializer.Serialize(placeList);
            ViewBag.Places = sJSON;

在视图中它的渲染输出是这样的:

[{&quot;title&quot;:&quot;sdf sdfsd sdf sd f&quot;,&quot;description&quot;:&quot;sdf sdf sd fsd sd sdf sdf dssd sdf sd s&quot;,&quot;latitude&quot;:53.740259851464685,&quot;longitude&quot;:-2.4602634343627927},

如何让它在视图中呈现为正常的 json?减去&amp;quot;etc?

【问题讨论】:

    标签: c# asp.net-mvc json


    【解决方案1】:

    在您下面的评论中,您说您的视图正在使用@ViewBag.Places

    你在使用 Razor 吗?如果是这样,@ 语法的作用与&lt;%: 相同——它对内容进行编码。

    使用IHtmlString 接口来避免它,所以要么:

    ViewBag.Places = new HtmlString(sJSON);
    

    或者

    @HtmlString(ViewBag.Places)
    

    【讨论】:

      【解决方案2】:
      @Html.Raw(ViewBag.Places)
      

      也可以

      【讨论】:

        【解决方案3】:

        你试过了吗?

        string sJSON = HttpServerUtility.HmltDecode(oSerializer.Serialize(placeList));
        

        【讨论】:

        • 我也认为 oSerializer.Serialize 返回 html 编码字符串很奇怪。你确定你的视图中的渲染没有任何预处理?
        • 我试过了:HttpUtility.HtmlDecode(oSerializer.Serialize(placeList)); - 结果相同
        • 在我看来我有:“places”:@ViewBag.Places
        • 你试过 吗? (我不使用剃须刀)
        猜你喜欢
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-10
        相关资源
        最近更新 更多