2

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.

2
  • 1
    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) Commented Feb 16, 2018 at 8:42
  • I would suggest making an ajax request and getting those users as a json object. Commented Feb 16, 2018 at 8:52

4 Answers 4

1

I think there is a better approach to your problem. You are asking how to pass the values from the controller in your view. Your approach will work but it would be much simpler to pass the object as your model for the view. When you return the View(), you need to pass the objects that contains your list. Like this: return View(users); Then, in your view you need to register your model @model IEnumerable<User>() After that with a simple foreach you can iterate the model and display the values:

@foreach(var item in Model){
    //do whatever you want with the item
}

If you need the model elements into your nodes variable you can do it like this:

<script>
var nodes = @Html.Raw(Json.Encode(Model))
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It works for me. But reason of using ViewBag is that I need not only User's list in my js code.
0

You can use below code to achieve this.

var nodes = function () {
  var array = [];
  @for(int i = 0; i < 5; i++) {
     <text>
       array.push({"name": "@ViewBag.Users[i].Name", "group": "@ViewBag.Users[i].Group"})
     </text>
  }
  return array;
}

Try surrounding your js with <text></text>

Reference: How can a razor for loop be used in a javascript script tag?

Comments

0

You can serialize your list of users as JSON object. I think that this is what you are trying to get as a result. The easiest way it this.

ViewBag.Users = JsonConvert.SerializeObject(users);

I have created a .net fiddle with your example. Please check it HERE.

You will need to include Newtonsoft.Json NuGet package for this code. If you don't want to use this package, you can use JavaScriptSerializer.Serialize Method from System.Web.Scripts.Serialization. Click here for more info.

Comments

0
var nodes= JSON.stringify(@Html.Raw(Json.Encode(ViewBag.Users)));

1 Comment

You should add an explanation of how the shown code answers the question. Take a look at the other answers for inspiration on how to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.