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

nHi Guys,
n
nThis 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.
n
nScenario:
nAll I was trying to do was to initialize collection of strings in the controller and wanted to pass this collection to the view.
nView was having the JavaScript function which required to have this collection in the form of array.
n
nAfter searching around this I found a solution which is a single liner :).
n
nHere is my controller where I have simply initialized the string collection and passing through the ViewBag on the view
n
nController:
n
n
n

npublic ActionResult Index()

n

n{

n

n   List<string> entites = new List<string>();

n

n  nentites.Add(“User 1”);

n

n  nentites.Add(“User 2”);

n

n  nentites.Add(“User 3”);

n

n  nentites.Add(“User 4”);

n

n

n

n  nViewBag.Users = entites;

n

n   return View();

n

n

n

n}

n

n

n

n

n

nView / JavaScript:

n

n

n

n

n

n<script>

n

n    $(document).ready(function ()

n

n    {

n

n        var usersArray = @Html.Raw(Json.Encode(ViewBag.Users))

n

n           

n

n        //Some Code..

n

n

n

n

n

n    });

n

n</script>

n

n

n

nOutput:

n

n

n

n

n

nvar usersArrayn= [“User 1”,“User 2”,“Usern3”,“User 4”]

n
n

n

n
n

n

n

nHope this helps someone.

n

Leave a Comment