2011-06-01 50 views
0
@using (Ajax.BeginForm("Create", "Comment", 
    new AjaxOptions 
    { 
     UpdateTargetId = "newComment", 
     OnSuccess = "function() { alert('finished " + ViewData.Model.Id + "'); }", 
    })) 
{ 
    ... 
} 

輸出以下標記:防止Ajax.BeginForm從HTML編碼輸出

<form action="/Comment/Create" data-ajax="true" data-ajax-mode="replace" 
data-ajax-success="function() { alert(&#39;finished 34&#39;); }" 
data-ajax-update="#newComment34" id="form1" method="post"> 

正如你所看到的,它具有HTML編碼我的JavaScript。我如何防止這種情況?

編輯:我在我的頁面上有多個AJAX表單,所以onsuccess函數需要知道哪一個叫它。在我的代碼中,你可以看到我試圖將狀態傳遞給這個函數。如果OnSuccess只能使用一個函數名(而不是狀態),那我該如何實現呢?

回答

2

個人而言,我會用一個標準Html.BeginForm幫手與HTML5 data-*屬性,我將AJAXify自己:

@using (Html.BeginForm(
    "Create", 
    "Comment", 
    FormMethod.Post, 
    new { data_id = Model.Id } 
)) 
{ 
    ... 
} 

,輸出:

<form action="/Comment/Create" data-id="some id here" method="post"> 
    ... 
</form> 

,然後在一個單獨的JavaScript文件我將認購.submit事件:

$(function() { 
    $('form').submit(function() { 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      dataId: $(this).data('id'), // <- pass the data-id HTML5 attribute 
      success: handleSuccess 
     }); 
     return false; 
    }); 
}); 

function handleSuccess(result) { 
    $('#newComment').html(result); 

    // fetch the data-id of the form that trigerred the AJAX request 
    var id = this.dataId; 

    // TODO: do something with this id 
} 

我喜歡這種技術,與Ajax.*傭工相比,因爲它給了我可能需要的所有控制。另一個優點是我們清楚地區分了腳本和標記,使代碼更加整潔。

+0

感謝您的解決方法。 – 2011-06-01 07:18:08

0

不要。

HTML編碼是正確的行爲,並且屬性值(如從Javascript代碼中看到的)將不會被編碼。

0

我相信這是因爲MVC將OnSuccess(和其他變量)解釋爲Javascript函數的名稱,而不是一點Script。

做一個幫助函數,執行您想要對提交進行操作的腳本。

+0

那麼我該如何將狀態傳遞給這個函數呢?我的頁面上有多個這樣的ajax表單,而成功函數需要知道哪個表單調用了它。 – 2011-06-01 00:35:56