如何更新Ajax.BeginForm一个div并执行javascript函数? [英] How to update a div with Ajax.BeginForm AND execute a javascript function?
问题描述
我用这样的更新与局部视图的div:
I am updating a div with a partial view by using something like this:
<% using (Ajax.BeginForm("Action", "Controller",
new { id=Model.id },
new AjaxOptions
{
UpdateTargetId = "divId",
InsertionMode = InsertionMode.InsertAfter,
}))
{ %>
和它的做工精细,返回的视图获取appened到div,但我现在需要的时候后成功执行JavaScript,因此我想:很简单,只要添加的onSuccess =MyJsFunc ()
到 AjaxOptions
,但是这样做之后,就停止工作! 及其工作也不..我怎么能现在刷新页面,只有返回的局部视图渲染:(,我甚至尝试用一个简单的警报(你好)得到这个工作?
and its working fine, the returned view gets appened to the div, however I now need to execute a javascript when the post is successful, so I thought: "easy, just add OnSuccess = "MyJsFunc()"
" to the AjaxOptions
, but after doing this, it stopped working! now the page is refreshed and only the returned partial view is rendered :(, I even tried with a simple Alert("Hi")
and its nor working.. how can I get this to work?
(顺便说一句,我认为这可能是<一个一个DUP href=\"http://stackoverflow.com/questions/1994754/execute-javascript-after-loading-a-mvc-page-using-ajax-beginrouteform\">http://stackoverflow.com/questions/1994754/execute-javascript-after-loading-a-mvc-page-using-ajax-beginrouteform但这个问题得到了摒弃没有答案)
(by the way I think this can be a dup of http://stackoverflow.com/questions/1994754/execute-javascript-after-loading-a-mvc-page-using-ajax-beginrouteform but that question got abandoned with no answer)
推荐答案
任何理由不这样做是正确的方式(毕竟我们是在2010年)?转储MS AJAX它属于哪里以及所有阿贾克斯,这依赖于它的*
助手和写入正确的code。而在经典的web表单使用MS AJAX可能已经因为UpdatePanel的,等等......今天做一个新的ASP.NET MVC应用程序,尤其是在微软已经完全接受的jQuery合理的,似乎是一个坏主意。
Any reason for not doing it the right way (after all we are in 2010)? Dump MS AJAX where it belongs along with all the Ajax.*
helpers which depend on it and write proper code. While using MS AJAX in classic webforms could have been justified because of the UpdatePanels, etc... doing it in a new ASP.NET MVC application today, especially after Microsoft have fully embraced jQuery, seems like a bad idea.
所以咆哮后,这里是我的建议:
So after the rant here's my recommendation:
<% using (Html.BeginForm("Action", "Controller", new { id = Model.id }) { %>
,然后装上提交处理程序悄悄地使用jQuery在一个单独的文件:
and then attach the submit handler unobtrusively using jquery in a separate file:
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
success: function(result) {
// feel free to execute any code
// in the success callback
$('#result').html(result);
}
});
return false;
});
});
或使用优秀的jQuery插件的形式:
$(function() {
$('form').ajaxForm(function(result) {
// feel free to execute any code
// in the success callback
$('#result').html(result);
});
});
这种方法的优点:
Benefits of this approach:
- 不显眼
- 标记和JavaScript之间的明确分离
- 缓存JavaScript文件,减少带宽使用
奖金的好处:没有头痛
这篇关于如何更新Ajax.BeginForm一个div并执行javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!