本文介绍了将列表编码为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Razor Engine将List<T>Session["MySession"]编码为JSON.

Encode a List<T>Session["MySession"] to JSON with Razor Engine.

我的Index.cshtml中包含以下脚本:

<script type="text/javascript">
    var existingItems =
        @Html.Raw
           (Json.Encode
              ((List<MyApp.Models.Data.getSpecificProductToShoppingList_Result>)
                  Session["ProdructsSummary"]))

    window.onload = function () {
        console.log(existingItems);
    }
</script>

existingItems的返回值为null.为什么?

And the return of existingItems is null. Why?

我确定-我的会话中有一个值.

I'm sure — there is a value on my Session.

推荐答案

您无需强制转换为基础类型.您可以简单地写:

You don't need to cast to the underlying type. You could simply write:

<script type="text/javascript">
    var existingItems = @Html.Raw(Json.Encode(Session["ProdructsSummary"]));

    window.onload = function () {
        console.log(existingItems);
    }
</script>

现在您说的是,这会生成以下标记:

Now you are saying that this generates the following markup:

<script type="text/javascript">
    var existingItems = null;

    window.onload = function () {
        console.log(existingItems);
    }
</script>

那呢:

<script type="text/javascript">
    @if (Session["ProdructsSummary"] == null)
    {
        <text>alert('the session is null');</text>
    }
</script>

您可以看到警报吗?我确定您可以看到它.假设您关于获取null的说法是正确的,我什至愿意下注5美元.

Can you see the alert? I am sure you can see it. I am even ready to bet 5 bucks on it assuming your statement about getting null is true.

结论:Session["ProdructsSummary"]为空,所以不要指望Json.Encode会返回其他内容.

Conclusion: Session["ProdructsSummary"] is null so don't expect that Json.Encode will return something else.

这篇关于将列表编码为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:44