2011-07-14 213 views
2

有沒有辦法提交一個表單,但它仍然在頁面上?MVC3 Ajax調用控制器

現在我正在顯示一個對象表,但每行都有一個可編輯的值,每行都有它自己的Ajax表單,但是當我單擊更新按鈕時,它會轉到方法,但整個頁面都會更改。

回答

7

無論如何提交表單,但它仍然在網頁上?

當然,你可以使用AJAX:

@using (Html.BeginForm()) 
{ 
    ... some form input fields 

    <input type="submit" value="Go" /> 
} 

,然後悄悄地AJAXify這種形式在一個單獨的文件:

$(function() { 
    $('form').submit(function() { 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      success: function(result) { 
       // TODO: handle the results of the AJAX call 
      } 
     }); 
     return false; 
    }); 
}); 

,並避免編寫這一切的JavaScript代碼,您可能需要看看優秀jquery.form plugin

$(function() { 
    $('form').ajaxForm(function(result) { 
     // TODO: handle the results of the AJAX call 
    }); 
}); 

另一種方法是使用ASP.NET MVC 3 Ajax.BeginForm幫手:

@using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "success" })) 
{ 
    ... some form input fields 

    <input type="submit" value="Go" /> 
} 

,然後有一個JavaScript成功處理程序:

function success(result) { 
    // TODO: handle the results of the AJAX call 
} 

您還需要包括jquery.unobtrusive-ajax.js腳本除了jquery到您的頁面,如果你想使用Ajax.*助手。

+0

其實,只需要添加jquery.unobtrusive-ajax.js腳本,但非常感謝您的幫助。我一直在拉我的頭髮(或剩下的)。 – MCBrandenburg