2013-03-12 44 views
0

我已經提到Steven Sanderson's blog,並試圖實現在鏈接的點擊事件上動態插入控件。現在在我的情況下,它不工作。我不知道它有什麼問題。刪除Div(包括控件)工作正常。但追加控件無效。當我點擊「添加更多」鏈接時,它會在新頁面上打開。不在同一頁面上呈現添加控件。Ajax請求不適用於動態控制追加

我的MainView代碼:

<div id="Div1"> 
    <% Html.RenderAction("_EditServices", "CRM", new { id = Model.Id });%> 
</div> 
<div id="editorRows"> 
    <% Html.RenderAction("_EditInsertServices", "CRM"); %> 
</div> 
<%= Html.ActionLink("+ Add More Service(s)", "EditAdd", null , new { id = "addItem" })%> 

我對_EditInsertServices PartiaView:

<div class="editorRow"> 
<% using (Html.BeginCollectionItem("services")) 
    { %> 
    NOS:<%:Html.DropDownListFor(model=>model.Id,(SelectList)ViewData["crmServiceType"] as SelectList,"---")%> 
    Comment:<%=Html.TextBoxFor(model => model.Comment, new { size = "20" })%> 
    <a class="deleteInsertRow">delete</a> 
    <% } %> 
</div> 

我的控制器代碼:

public ActionResult EditAdd() 
{ 
    ViewData["crmServiceType"] = new SelectList(CRMRequestDL.GetCRM_Service_TypeList().ToArray(), "Id", "ServiceName"); 
    return View("_EditInsertServices", new CommentedService()); 
} 
public ActionResult _EditInsertServices() 
{ 
    ViewData["crmServiceType"] = new SelectList(CRMRequestDL.GetCRM_Service_TypeList().ToArray(), "Id", "ServiceName"); 
    return PartialView(); 
} 

腳本:

<script type="text/javascript"> 
    $("#addItem").click(function() { 
     $.ajax({ 
      url: this.href, 
      cache: false, 
      success: function (html) { $("#editorRows").append(html); } 
     }); 
     return false; 
    }); 
    $("a.deleteInsertRow").live("click", function() { 
     $(this).parents("div.editorRow:first").remove(); 
     return false; 
    }); 
</script> 
+0

你用什麼版本的jQuery? – 2013-03-12 08:52:13

+0

您是否檢查了控制檯1)您沒有錯誤2)請求的頁面是否正確接收? – 2013-03-12 08:53:26

+0

@dystroy,我沒有收到任何錯誤期望「ReferenceError:$未定義」,而我點擊添加更多鏈接。我認爲Html.ActionLink可能存在問題。我的jQuery版本是1.9 – Dhwani 2013-03-12 08:55:24

回答

0

我解決了它的jQuery 1.9

使用on

$('#editorRows').on("click", "a.deleteInsertRow",function() { 
    $(this).parents("div.editorRow:first").remove(); 
    return false; 
}); 

被刪除。其實我把$(「#addItem」)。click(function(){});函數轉換爲$(document).ready(function(){});功能,它工作正常。因此,無論何時我使用$(「any class/id」),我都應該將該方法放在$(document).ready()函數中。

這裏是解決方案:

<script type="text/javascript"> 
$(document).ready(function() { 
    $("#addItem").click(function() { 
    $.ajax({ 
    url: this.href, 
    cache: false, 
    success: function (html) { $("#editorRows").append(html); }}); 
    return false; 
    }); 
}); 
</script> 
1

現場()已被廢棄,如果你想read更多有關事件

+0

我的添加控件無效。去除Div工作正常。 – Dhwani 2013-03-12 08:30:57