Where and when do you want this data?
If you want this in your view, just pass the data to the view
Action / Controller:
public ActionResult MyAction() { ViewData["MyData"] = "this is a sample data of type string"; return View(); }
And then, somewhere in your opinion:
<script> var data = '<%= ViewData["MyData"] %>'; $(document).ready(){ alert(data); } </script> <h1><%: ViewData["MyData"] %></h1>
Of course, if you are working with List<string> or `string [] ', you need to format it for proper JavaScript for jQuery to understand it.
<script> var dataArray = [ <% foreach(string s in (string[])ViewData["MyDataArray"]){ %> <%= s %>, <% } %> ]; </script>
This will getter if you created the correct JavaScript in action instead of the view, to avoid the ugly markup in your view:
public ActionResult MyAction() { string[] myArray = new string[]{ "hello", "wolrd" }; ViewData["MyData"] = myArray; ViewData["JavaScriptArray"] = "[" + myArray.Aggregate((current,next) => string.Format("'{0}','{1}',", current, next).TrimEnd(new char[] { ','})) + "]";
Now you can do the following on your screen:
<script> var dataArray = <%= ViewData["MyJavaScriptArray"] %>; alert(dataArray[0]); // alerts 'hello' </script>
Omar
source share