使用 Javascript 访问 ASP 会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6999298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:38:53  来源:igfitidea点击:

Accessing ASP Session Variables with Javascript

javascriptasp.netlistsessionvariables

提问by

I know I can reference a simple session variable (ie: string) in javascript like this:

我知道我可以像这样在 javascript 中引用一个简单的会话变量(即:字符串):

var SesVar = '<%= Session("MySessionVariable") %>';
alert(SesVar);

But the problem I have is that I have an ASP.NET generic list object stored in Session.Contents. The object looks like this:

但我遇到的问题是我在 Session.Contents 中存储了一个 ASP.NET 通用列表对象。该对象如下所示:

Public Class LetterReason

Private _reasonCode As String
Public Property ReasonCode() As String
    Get
        Return _reasonCode
    End Get
    Set(ByVal value As String)
        _reasonCode = value
    End Set
End Property

Private _reason As String
Public Property Reason() As String
    Get
        Return _reason
    End Get
    Set(ByVal value As String)
        _reason = value
    End Set
End Property

I've stored a list of this object in session contents like so:

我在会话内容中存储了这个对象的列表,如下所示:

Dim lsReasons As New List(Of LetterReason)

lsReasons = MyWCF.Get(reasons)

Session.Contents("lsReasons") = lsReasons    

Problem is, when I use the code above (SesVar), it returns this:

问题是,当我使用上面的代码 (SesVar) 时,它返回:

System.Collections.Generic.List`1[LetterWriterASP2.ServiceReference1.LetterReason]

Is there any way I can access a list stored in session contents through javascript?

有什么方法可以通过javascript访问存储在会话内容中的列表?

Thanks,

谢谢,

Jason

杰森

采纳答案by nicodemus13

The problem is that the evaluation binding tag will automatically call the ToString() method on the whatever it finds in the Sessionobject.

问题是评估绑定标签将自动调用它在Session对象中找到的任何内容的 ToString() 方法。

So, if:

因此,如果:

var SesVar = '<%= Session("MySessionVariable").ToString() %>';

has a meaningful implementation (e.g. it is a string, or a value type), then you'll get what you expect.

有一个有意义的实现(例如它是一个字符串,或一个值类型),那么你会得到你所期望的。

However, in your example, you're storing an instance of the class, LetterReason, for which the default objectToString() virtual method call will return the name of the class.

但是,在您的示例中,您正在存储类的一个实例,LetterReason默认objectToString() 虚拟方法调用将返回类的名称。

The answer depends what you want to do with the result. You can't trivially use a .NET object in JavaScript, the data is going over a domain boundary (i.e. out of your .NET website and over the network and then into the DOM of a HTML page).

答案取决于您想对结果做什么。您不能在 JavaScript 中随意使用 .NET 对象,数据会跨越域边界(即离开您的 .NET 网站并通过网络,然后进入 HTML 页面的 DOM)。

You will need to serialise it in some way, probably JSON. Use an approach like this: Can you Instantiate an Object Instance from JSON in .NET?

您需要以某种方式序列化它,可能是 JSON。使用这样的方法:Can you Instantiate an Object Instance from JSON in .NET?

That's if you need all the richness of the class. If you're just looking for specific properties/methods, you could have:

那就是如果您需要课程的所有丰富性。如果您只是在寻找特定的属性/方法,您可以:

var reasonCode = '<%= ((LetterReason)Session("MySessionVariable")).ReasonCode() %>';
var reason = '<%= ((LetterReason)Session("MySessionVariable")).Reason() %>';

So, here you'll need to cast your session instance to your particular class (plain .net System.Objectare stored in the Sessions, giving you maximum flexibility) and then take the property you want.

因此,在这里您需要将会话实例转换为您的特定类(普通 .netSystem.Object存储在会话中,为您提供最大的灵活性),然后获取您想要的属性。

However, serialising the object from .NET to JSON would be much the best solution, as it's flexible and maintainable.

但是,将对象从 .NET 序列化为 JSON 将是最好的解决方案,因为它灵活且可维护。

回答by Aaron Barker

Typically I handle client/server communications (such as accessing state on the server) asynchronously using a combination of WebServices and JQuery. This pattern has a very small payload when compared to the built in asp.net AJAX toolkit and will handle your scenario very well.

通常,我使用 WebServices 和 JQuery 的组合异步处理客户端/服务器通信(例如访问服务器上的状态)。与内置的 asp.net AJAX 工具包相比,此模式的有效负载非常小,并且可以很好地处理您的场景。

This article is a great example to get started: http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

这篇文章是一个很好的入门示例:http: //encosia.com/using-complex-types-to-make-calling-services-less-complex/

回答by dtackett

Your going to need to Serialize that list into XML or JSON or somthing parsable. Dumping a complex session var onto a page like in your sample is basically doing a ToString() on the list instance, which will spit out nothing you can use.

您需要将该列表序列化为 XML 或 JSON 或可解析的内容。将复杂的会话变量转储到您的示例中的页面上基本上是在列表实例上执行 ToString() ,它不会输出您可以使用的任何内容。

回答by James Johnson

You cannot access your list that way, because the object you're storing in Session is specific to .NET, and JavaScript doesn't know what it is or how to parse it. You would need to convert the array to something more universally understood, like a delimited string or something along those lines.

您无法以这种方式访问​​您的列表,因为您存储在 Session 中的对象特定于 .NET,而 JavaScript 不知道它是什么或如何解析它。您需要将数组转换为更普遍理解的内容,例如分隔字符串或类似的内容。

回答by Brian

Try JSON serializing the value - here's a helper method I wrote:

尝试 JSON 序列化值 - 这是我写的一个辅助方法:

public static string JsonSerialize<T>(T tItem)
{
    if (null == Attribute.GetCustomAttribute(typeof(T), typeof(DataContractAttribute)))
    {
        bool canSerialize = false;
        if (typeof(T).IsGenericType)
        {
            foreach (Type t in typeof(T).GetGenericArguments())
            {
                if (t.IsPrimitive)
                {
                    canSerialize = true;
                }
                else if (!(null == Attribute.GetCustomAttribute(t, typeof(DataContractAttribute))))
                {
                    canSerialize = true;
                }
                else
                {
                    canSerialize = false;
                    break;
                }
            }
        }

        if (canSerialize == false)
        {
            throw new SerializationException(String.Format("Cannot JsonSerialize instance of type {0} because {0} is not decorated as a DataContract.", typeof(T).FullName));
        }
    }

    string sResult = String.Empty;
    try
    {
        DataContractJsonSerializer jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            jsonSerializer.WriteObject(ms, tItem);
            sResult = System.Text.Encoding.Default.GetString(ms.ToArray());
        }
    }
    catch
    {
        throw;
    }
    return sResult;
}

Then, on the client side, use ASP.NET's client side library to deserialize:

然后,在客户端,使用 ASP.NET 的客户端库进行反序列化:

Sys.Serialization.JavaScriptSerializer.deserialize(mySessionVarString, false);