Encode List to JSON

2019-08-29 04:05发布

The Goal

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

The Problem

I have the following script in my 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>

And the return of existingItems is null. Why?

Observation

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

1条回答
贪生不怕死
2楼-- · 2019-08-29 04:31

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>

What about this:

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

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.

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

查看更多
登录 后发表回答