How To Use C# List In Javascript
Today, I want to talk about using C# List in javascript. If you have an Asp.Net MVC Web App, you need to send a list of data from controller to your html page. Now I will explain how to use C# list in javascript.
First we must prepare our list data in controller. As a result, I prepared this controller code for my Razor view. I will send “myList” data to the Razor view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public ActionResult Home() { HomeViewModel model = new HomeViewModel(); List<Person> myList= new List<Person>(); Person element= new Person(); element.Name= "Alex"; element.Surname= "Anderson"; element.Id = 123; myList.Add(element); System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); model.JSONList= oSerializer.Serialize(myList); return View(model); } |
We must serialize the list to javascript can understand and use it in our html page. This is our javascript code :
1 2 3 4 5 6 7 8 9 10 11 12 |
function Draw() { var tunel = JSON.parse('@Html.Raw(Model.JSONList)'); var str = ""; if (tunel.length > 0) { for (var i = 0; i < tunel.length; i++) { str += '<span>' + tunel[i].Name + '</span>'+ '<span>' + tunel[i].Surname + '</span>'+ '<span>' + tunel[i].Id + '</span>'; } $("#myDiv").append(str); } } |
Let me explain this code. We must convert this code with “Html.Raw” to escape from quotation marks etc. Without that, list data treats like string. And we have to parse it with “json.parse” to make this list data usable for javascript. You should have a look at my another post about Session Authorization In Asp.Net
Recent Comments