传递List<int>从代码隐藏到Javascript函数中使用

Pass List<int> from code behind to use in Javascript function

本文关键字:Javascript 函数 隐藏 List int 传递 代码      更新时间:2023-09-26

目前我有一个Javascript函数,它使用我可以硬编码值,例如 -

data: [1,4,7,9]

但是,我希望传入一个整数列表,以设置代码后面的值,例如 -

C# 代码隐藏

public List<int> listOfInts = new List<int>();
protected void Button1_Click(object sender, EventArgs e)
    {
        listOfInts.Add(1);
        listOfInts.Add(4);
        listOfInts.Add(7);
        listOfInts.Add(9);
        ScriptManager.RegisterStartupScript(this, GetType(), "blah", "JSfunction()", true);
    }

阿斯普克斯

data: <% = listOfInts %>

然而,这打破了错误 -

0x800a1391 - Microsoft JScript runtime error: 'JSfunction' is undefined

如果我删除上述行并在函数中这样做(不像我需要的那样从后面的代码中传递任何东西)-

var listOfInts = new Array(); 
listOfInts[0] = 1;
listOfInts[1] = 2; 
listOfInts[2] = 3; 
listOfInts[3] = 4;

然后设置 -

data: [listOfInts[0],listOfInts[1],listOfInts[2],listOfInts[3]]

这工作正常。如何从后面的代码中传递值以填充 Javascript 函数中的值?

您需要将 listOfInts 格式化为 javascript 数组。尝试在代码隐藏中添加属性,如下所示:

protected string IntsAsJSArray
{   
    get 
    {
        return string.Format("[{0}]", string.Join(",", listOfInts));
    }
}

然后在您的 ASPX 页面中

data: <%= IntsAsJSArray %>

一个更通用的方法...在我看来,更好的做法是编写适用于您需要执行此操作的任何对象的东西。 请考虑以下扩展方法...

    public static T FromJson<T>(this string jsonData, Encoding encoding = null) 
        where T : class
    {
        encoding = encoding ?? Encoding.Default;
        var deserializer = new DataContractJsonSerializer(typeof(T));
        var buffer = encoding.GetBytes(jsonData);
        using (var stream = new MemoryStream(buffer))
        {
            return deserializer.ReadObject(stream) as T;
        }
    }
    public static string ToJson<T>(this T obj, Encoding encoding = null) 
        where T : class
    {
        encoding = encoding ?? Encoding.Default;
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, obj);
            return encoding.GetString(stream.ToArray());
        }
    }

那么在您的情况下,用法如下所示...

data: <% = listOfInts.ToJson() %> 

无论您的 asp.net 端有 List、Int[] 或任何其他对象,这都有效。 另外,不要忘记考虑 JSON 文本的编码方式。