HowTo pass List<T> object to Javascript in MVC?
I wanna do something like that:
$(document).rea开发者_如何学Gody(function ()
{
calendarGrid.create(@Model.Events)
}
Model.Events is a List.
I tried to use:
- System.Web.Script.Serialization.JavaScriptSerializer.Serialize(@Model.Events)
- JSON.parse(@Model.Events)
- JSON.strigngify(@Model.Events)
nothing helps.
You need to write code that will serialize your server-side list into code that gets sent to the client. Trye something like this:
calendarGrid.Create(@Html.Raw(JavaScriptSerializer.Serialize(Model.Events)))
The entire contents of @Html.Raw(...)
will be emitted to the output.
I've had great success by setting a javascript variable to it, using:
<script>
var eventList = @(Html.Raw(Json.Encode(Model.Events)));
$(document).ready(function () {
calendarGrid.create(eventList);
});
</script>
From there, you can freely use the eventList variable as a JSON object.
The Trick is the use of Html.Raw to prevent any further encoding from happening
精彩评论