2011-07-14 48 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