开发者

HowTo pass List<T> object to Javascript in MVC?

开发者 https://www.devze.com 2023-02-25 16:39 出处:网络
I wanna do something like that: $(document).rea开发者_如何学Gody(function () { calendarGrid.create(@Model.Events)

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

0

精彩评论

暂无评论...
验证码 换一张
取 消