C# 在c语言中将对象集合转换为javascript数组的创造性方法
我有一个用户列表,我需要创建一个包含所有用户ID的javascript数组 我知道我可以使用stringbuilder手动构建它并循环,然后将其保存到变量并显示在我的asp.net-mvc视图页面上C# 在c语言中将对象集合转换为javascript数组的创造性方法,c#,javascript,asp.net-mvc,arrays,json,C#,Javascript,Asp.net Mvc,Arrays,Json,我有一个用户列表,我需要创建一个包含所有用户ID的javascript数组 我知道我可以使用stringbuilder手动构建它并循环,然后将其保存到变量并显示在我的asp.net-mvc视图页面上 还有其他更有创意的方法吗 您可以使用Jsonlist转换为JSON,然后在javascript中解析它您可以使用Jsonlist转换为JSON,然后在javascript中解析它JsonConvert.Serialized对象,从 下面的简化示例: using System; using Syste
还有其他更有创意的方法吗 您可以使用Jsonlist转换为JSON,然后在javascript中解析它您可以使用Jsonlist转换为JSON,然后在javascript中解析它JsonConvert.Serialized对象,从 下面的简化示例:
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
class Users
{
public string Name {get; set;}
public int UserID {get; set;}
public Users(string Name, int UserID)
{
this.Name = Name;
this.UserID = UserID;
}
}
List<Users> users = new List<Users>();
users.Add(new Users("John", 1));
users.Add(new Users("Mary", 2));
...
string json = JsonConvert.SerializeObject(from user in users select user.UserID);
}
JsonConvert.SerializeObject,来自 下面的简化示例:
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
class Users
{
public string Name {get; set;}
public int UserID {get; set;}
public Users(string Name, int UserID)
{
this.Name = Name;
this.UserID = UserID;
}
}
List<Users> users = new List<Users>();
users.Add(new Users("John", 1));
users.Add(new Users("Mary", 2));
...
string json = JsonConvert.SerializeObject(from user in users select user.UserID);
}
你也可以这样做
var jsArray = String.Format("var userIds=new Array({0});", String.Join(",", users.Select(x =>x.UserId.ToString()).ToArray()))
你也可以这样做
var jsArray = String.Format("var userIds=new Array({0});", String.Join(",", users.Select(x =>x.UserId.ToString()).ToArray()))