Heriniaina
Heriniaina

Reputation: 35

How to print javascript array with Model list

with asp .net mvc5, how to recover the model in javascript? here are my codes

Ctrl:

public ActionResult Test() {

    var data = List<string>() {
        "test",
        "essai"
    };

    return View(data); 
}

View:

@model ...

@section scripts {
    <script src="~/Scripts/Parametre/DatePublication.js"></script>
}

Partial Js:

$(document).ready(function () {
    console.log(@Model);
});

The @Model in partial Js is not found.

Upvotes: 1

Views: 4613

Answers (2)

Shyju
Shyju

Reputation: 218752

Model will work only in razor views which can execute server code. If you want this as a javascript array in an external javascript file, you may read it to a js array variable inside a razor view and use it later in other scripts

 <script>
     var myArray = @Html.Raw(JsonConvert.SerializeObject(Model))
     console.log(myArray);
 </script>
 <script src="ExternalJsFile.js"></script>

You can access myArray in ExternalJsFile.js now.

Passing data via simple global variables are not a great idea. They are prone to get overwritten.(What if some thirdparty plugin script you load is also using the same variable name ? ) So you should consider namespacing your data to be safe.

For example,

 <script>
     var myApp = myApp || {};  
     myApp.pageData = myApp.pageData || {};
     myApp.pageData.model = @Html.Raw(JsonConvert.SerializeObject(Model));
 </script>
 <script src="ExternalJsFile.js"></script>

Now in the externalJs file, you can access it like console.log(myApp.pageData.model)

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You cannot do this in Razor, because in Razor every content using a @ block is automatically HTML encoded by Razor.

The solution is to iterate your list and create a javascript array.

var myArray = [];
@foreach (var item in Model)
{
    @:myArray.push('@item');
}
console.log(myArray);

Inside the @foreach block, you need to mark the markup or Javascript using @: markup or <text> tag.

Upvotes: 1

Related Questions