views:

339

answers:

3

Hi,

I have a List of users List<Users> and I need to make a javascript array of all the UserID's.

I know I can manually build this using a stringbuilder and loop through and then save it to a variable and show it on my asp.net-mvc view page.

Any other more creative ways to do this?

+1  A: 

you can covert into JSON using Json(list) and then parse it in your javascript

Rony
+5  A: 

JsonConvert.SerializeObject, from Json.NET.

Simplified example below.:

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);
}
Matthew Flaschen
+1  A: 

also you can do it this way

var jsArray = String.Format("var userIds=new Array({0});", String.Join(",", users.Select(x =>x.UserId.ToString()).ToArray()))
Gagarin