我正在使用类似这样的方法更新带有部分 View 的 div:
<% using (Ajax.BeginForm("Action", "Controller",
new { id=Model.id },
new AjaxOptions
{
UpdateTargetId = "divId",
InsertionMode = InsertionMode.InsertAfter,
}))
{ %>
它工作正常,返回的 View 被附加到 div,但是我现在需要在发布成功时执行 javascript,所以我想:“简单,只需添加 OnSuccess = “MyJsFunc()”
"到 AjaxOptions
,但是这样做之后,它停止工作了!现在页面已刷新,只呈现返回的部分 View :(,我什至尝试使用简单的 Alert("Hi")
并且它不起作用..我怎样才能让它工作?
(顺便说一下,我认为这可能是 https://stackoverflow.com/questions/1994754/execute-javascript-after-loading-a-mvc-page-using-ajax-beginrouteform 的复制品,但这个问题没有得到答案就被放弃了)
最佳答案
有什么理由不以正确的方式去做(毕竟我们都在 2010 年)?将 MS AJAX 连同依赖于它的所有 Ajax.*
助手转储到它所属的位置,并编写适当的代码。虽然在经典的网络表单中使用 MS AJAX 可能是合理的,因为 UpdatePanels 等......今天在新的 ASP.NET MVC 应用程序中这样做,尤其是在微软完全接受 jQuery 之后,似乎是一个坏主意。
所以在咆哮之后这是我的建议:
<% using (Html.BeginForm("Action", "Controller", new { id = Model.id }) { %>
然后在单独的文件中使用 jquery 不引人注意地附加提交处理程序:
$(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 form plugin :
$(function() {
$('form').ajaxForm(function(result) {
// feel free to execute any code
// in the success callback
$('#result').html(result);
});
});
这种方法的好处:
- 不引人注目
- 明确区分标记和 javascript
- 缓存 javascript 文件并减少带宽使用
额外好处:没有头痛。
关于c# - 如何使用 Ajax.BeginForm 更新 div 并执行 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3840967/