In my actual task I need to create graph for app based on ASP.NET MVC. I found suitable js, but I forced a problem how to create js object from values, which are created in a controller. For example:
public class User
{
public string Name { get; set; }
public string Group { get; set; }
}
public ActionResult Index()
{
List<User> users = new List<User>()
{
new User{Name = "Boss", Group = "Boss"},
new User{Name = "Emp 1", Group = "Emps"},
new User{Name = "Emp 2", Group = "Emps"},
new User{Name = "Emp 3", Group = "Emps"},
new User{Name = "Emp 4", Group = "Emps"},
};
ViewBag.Users = users;
return View();
}
I have collection of User in my controller.
Below js code, which I need to create
var nodes = [
{ "name": "Boss", "group": "Boss" },
{ "name": "Emp 1", "group": "Emps" },
{ "name": "Emp 2", "group": "Emps" },
{ "name": "Emp 3", "group": "Emps" },
{ "name": "Emp 4", "group": "Emps" },
];
I want to I create js code like
var nodes = function () {
var array = [];
for (var i = 0; i < @ViewBag.Users.Count; i++) {
array.push({"name": @ViewBag.Users[i].Name, "group": @ViewBag.Users[i].Group})
}
return array;
};
P.S. This code not working because of i not exist.
var nodes = @Html.Raw(Json.Encode(ViewBag.Users))(note that your property names need to be lower case if that is what your want in the javascript objects)