最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - HowTo pass List<T> object to Javascript in MVC? - Stack Overflow

programmeradmin1浏览0评论

I wanna do something like that:

 $(document).ready(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.

I wanna do something like that:

 $(document).ready(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.

Share Improve this question asked Apr 15, 2011 at 18:59 iLemmingiLemming 36.4k61 gold badges198 silver badges316 bronze badges 1
  • What is the T? Is it serializable? – Jamie Treworgy Commented Apr 15, 2011 at 19:02
Add a ment  | 

2 Answers 2

Reset to default 3

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)

  1. 暂无评论