ASP NET从javascript读取会话

时间:2014-10-30 15:21:12

标签: javascript c# asp.net vb.net webforms

我有一个WebForms应用程序,我在Session对象中存储字符串数组,我需要 在javascript代码中获取此数组。也许有人可以提供任何解决方案,我该怎么做?

这是我的代码:

    function loadAnswers() {
        var answers = '<%=Session("answers")%>';
    }

但是不起作用,并且在赋值后,answers变量包含简单的字符串。 ( 'System.String []')

2 个答案:

答案 0 :(得分:1)

如果将answers对象序列化为JSON,那么您应该能够以编程方式从JavaScript访问它。

var answers = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Session("answers")) %>;

更新:以下是使用四种不同类型数据(字符串,数字,集合,对象)的工作示例。这说明了如何从服务器序列化的JSON可以用作JavaScript对象文字客户端。

<强>代码隐藏:

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

namespace WebFormsTestApp
{
    public partial class _Default : Page
    {
        protected string Name = "Alice Student";
        protected decimal GPA = 3.84M;
        protected List<string> Classes = new List<string>() { "World History", "Algebra II", "English", "Phys Ed", "Latin I", "Home Economics" };
        protected School School = new School() { Name = "Jefferson High School", County = "Hamilton County", Ranking = 5 };
    }

    public class School
    {
        public string Name { get; set; }
        public string County { get; set; }
        public int Ranking { get; set; }
    }
}

<强> ASPX:

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebFormsTestApp._Default" %>

<script type="text/javascript">
    var name = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Name) %>;
    var gpa = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(GPA) %>;
    var classes = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Classes) %>;
    var school = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(School) %>;
    alert(name + ' goes to ' + school.Name + ', has a ' + gpa + ' GPA, and takes ' + classes.length + ' classes.');
</script>

答案 1 :(得分:-1)

(我假设你使用VB)你可以使用这样的代码:

function loadAnswers() {
   var answers = ['<%= String.Join("','", CType(Session("answers"), String()))%>'];
}

它实际上将您的数组连接成一个字符串,格式化为JS数组表示。

例如,如果你有一个像这样的数组

Session("answers") = New String() {"aaa", "bbb", "ccc"}

它会产生这样一条线

var answers = ['aaa','bbb','ccc'];

这将是一个真正的JS阵列。如果您需要一个简单的字符串,可以使用

var answers = '<%= String.Join(",", CType(Session("answers"), String()))%>';

将产生

 var answers = 'aaa,bbb,ccc';