2010-10-08 100 views
0

我想返回一個局部視圖在asp mvc2呈現與火花。 該視圖包含一些JavaScript。 一切都被渲染,但劇本不執行aspmvc2使用火花引擎渲染partialview jQuery使用火花引擎

這裏是代碼

<table> 
<tr> 
<td> 
    !{Html.LabelFor(model => model.SourceId, new { @class = "label-inline", title = "Source d'ouvrage" })} 
    !{Html.DropDownList("SourceList", Model.SourceList, "Choisir la source", new { @class = "combo-box" })} 
</td> 
<td> 
    !{Html.LabelFor(model => model.AgentId, new { @class = "label-inline", title = "Représentant" })} 
    !{Html.DropDownList("AgentList", Model.AgentList, "Choisir le représentant", new { @class = "combo-box" })} 
</td> 
</tr> 

<script type="text/javascript"> 
$("#SourceList").change(function() { 
    alert('youpi'); 
    $.ajaxSetup({ cache: false }); 
     var selectedItem = $(this).val(); 
     alert(selectedItem); 
     if (selectedItem == "" || selectedItem == 0) { 
      //Do nothing or hide...? 
     } else { 
      var path = '~/sources/' + selectedItem + '/agents'; 
      $.getJSON(path, function(data) { 
       agents = data; 
       var items = ""; 
       $.each(data, function(i, agents) { 
        items += "<option value='" + agents.Id + "'>" + agents.Name + "</option>"; 
       }); 
       $("#AgentList").html(items); 
      }); 
     } 
    }); 
</script> 

我我我做錯了什麼? 謝謝

回答

0

jquery Ajax函數將從結果中去掉javascript並在將HTML插入到DOM之前運行它。

你的兩個最好的選擇是要麼

包裹JS在視圖上的非Ajax部位的功能(無論是視圖或部分這是在同一時間呈現),並調用這個函數爲您的成功你的阿賈克斯呼叫回調

或者替換$("#SourceList").change(function() {$("#SourceList").live('change', function() {儘管即使這樣做你仍然最好不包括它通過Ajax部分返回。

0

我會將腳本放入jQuery文檔就緒事件處理程序中,以便它在DOM完全加載後運行。它可能是該腳本在DOM創建您的#SourceList之前運行的。

例如:

<script type="text/javascript"> 
    $(function() { 
     $("#SourceList").change(function() { 
      ....