我有一个用户列表List<Users>
,我需要制作一个所有UserID的javascript数组。在c中将对象集合转换为javascript数组的创意方法#
我知道我可以使用一个stringbuilder手动构建这个,然后将其保存到一个变量并显示在我的asp.net-mvc视图页面上。
任何其他更有创意的方法来做到这一点?
我有一个用户列表List<Users>
,我需要制作一个所有UserID的javascript数组。在c中将对象集合转换为javascript数组的创意方法#
我知道我可以使用一个stringbuilder手动构建这个,然后将其保存到一个变量并显示在我的asp.net-mvc视图页面上。
任何其他更有创意的方法来做到这一点?
JsonConvert.SerializeObject,从Json.NET。下面:
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);
}
你可以隐蔽成JSON使用JSON(列表),然后分析它在你的JavaScript
也
简单的例子,你可以这样来做
var jsArray = String.Format("var userIds=new Array({0});", String.Join(",", users.Select(x =>x.UserId.ToString()).ToArray()))