Pages

Thursday, May 23, 2013

Passing String Collection or Array from Controller to View Script in MVC 4

Hi Guys,

This is going to be a short post but thought to just keep this for the record, as I had to search on this for some time.

Scenario:
All I was trying to do was to initialize collection of strings in the controller and wanted to pass this collection to the view.
View was having the JavaScript function which required to have this collection in the form of array.

After searching around this I found a solution which is a single liner :).

Here is my controller where I have simply initialized the string collection and passing through the ViewBag on the view

Controller:


public ActionResult Index()
{
   List<string> entites = new List<string>();
   entites.Add("User 1");
   entites.Add("User 2");
   entites.Add("User 3");
   entites.Add("User 4");

   ViewBag.Users = entites;
   return View();

}


View / JavaScript:

<script>
    $(document).ready(function ()
    {
        var usersArray = @Html.Raw(Json.Encode(ViewBag.Users))
           
        //Some Code..


    });
</script>

Output:

var usersArray = ["User 1","User 2","User 3","User 4"]




Hope this helps someone.

No comments:

Post a Comment