Pass IEnumerable List to javascript

I was wondering if I can pass the IEnumerable Collection to the Javascript method when the page loads. So something like this ...

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyAppMVC.Models.ViewModels.News.NewsIndexViewData>" %>

<div id="container">

    <%= String.Format("<script type='text/javascript'>testMethod({0})</script>", Model.NewsList)  %>

</div>

I understand that JS is the client side, I just did not know if there is a way to do this? Thanks!

+3
source share
2 answers

No, you can’t. For several reasons.

1) JavaScript IEnumerable, .NET. , -. .NET IEnumerable , GetEnumerator(), IEnumerator ( Current, MoveNExt Reset). JavaScript, , .

var myObj = { 'a' = 1, 'b' = 2 };

for (var name in myObj) { alert(name); } // will alert 'a', and 'b'

JavaScript , .

2) String.Format() , JavaScript, ToString() . , , "System.Collections.Generic.List`1 [System.String]"

3) , , . , JavaScript .NET-, .NET JavaScript. , -.NET , JavaScript ( ) (Compiled vs. ).

, , JavaScript. , , JSON. , Model.NewList, , testMethod() . , NewList - . JSON :

{ 'NewList' : ['string1', 'string2', 'string3'] }

.NET JSON - , JavaScriptSerializer:

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(Mdoel.NewList);
+8

javascript Page_Load (. , Model.NewsList - string enumeration array):

StringBuilder sb = new StringBuilder();
bool isFirst = true;
//build a comma seperated list.
foreach (string s in Model.NewsList)
{
    if (isFirst)
        isFirst = false;
    else
        sb.Append(", ");
    sb.Append("'").Append(s.Replace("'", "''")).Append("'");
}
//create the javascript array
string javascript = String.Format(@"var news = [{0}];", sb);
//put the array in the generated page.
Page.ClientScript.RegisterClientScriptBlock(GetType(), "newsList", javascript);

, javascript javascript.

0

Source: https://habr.com/ru/post/1719281/


All Articles