开发者

MVC3 render scripts in partial view

Hopefully someone out there can help me with this.....I'm building an MVC3 project and I can't seem to figure out why my partial view cannot execute any inline javascript functions. Here is made up example, but will hopefully show the principal I am trying to achieve....

I have a list of items in a view, called Items.

开发者_如何转开发
foreach (var item in Model.SaleItems)
{ 
  <div>@Html.ActionLink((string)item.ID, "Item", new { ID = @item.ID })</div>
}

If the user clicks one of the items, they will be sent to a page with details about the item selected. On this page, there is a menu will 3 choices; details, reviews, images (each is a partial view). If the user selects the details option from the menu, the details partial will render a few charts from a webservice like the Google visualization API.

Here is my partial view with a script to load a chart :

<div>
  <h4>Details</h4>
  <div id= "detailsContainer"></div>
 </div>


<script type="text/javascript">
   $(document).ready(function () {
    google.load('visualization', '1', { packages: ['table'] });
    google.setOnLoadCallback(drawDetailsTable);
    });
    function drawDetailsTable() {
      var data = new google.visualization.DataTable();
      data.addColumn('string', '');
      data.addColumn('string', '');
      data.addRows(4);
      data.setCell(0, 0, 'Color');
    data.setCell(0, 1, '<b>@Model.Color</b>');
    data.setCell(1, 0, 'Size');
    data.setCell(1, 1, '<b>@Model.Size</b>');
    data.setCell(2, 0, 'Weight');
    data.setCell(2, 1, '<b>@Model.Weight</b>');
    data.setCell(3, 0, 'Material');
    data.setCell(3, 1, '<b>@Model.MainMaterial</b>');
    var table = new google.visualization.Table(document.getElementById('detailsContainer'));
    var options = { allowHtml: true };
    table.draw(data, options);
}

</script>

Anyone have any ideas why this doesn't work? If I move the script from the partial view to the view, and statically declare an item in the main view's ActionResult, it will work, but other than that it doesn't.

Thanks in advance!


I finally figured it out. Shuniar was correct, scripts should execute in the partial views, but the problem is with the Google maps and visualization APIs. The partial view would render but the function that was never being called in the script. This make sense because there is no onLoad for partial views.

google.setOnLoadCallback(drawDetailsTable);
function drawDetailsTable() {
 ....
  });

To fix it, I simply changed it to explicitly call the function as the partial is being rendered.

    google.setOnLoadCallback(drawDetailsTable);
    drawDetailsTable();        
    function drawDetailsTable() {
 ....
  });     
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜