如何使用 Ajax.BeginForm 更新 div 并执行 javascript 函数?
我正在使用这样的方法更新带有部分视图的 div:
<% using (Ajax.BeginForm("Action", "Controller",
new { id=Model.id },
new AjaxOptions
{
UpdateTargetId = "divId",
InsertionMode = InsertionMode.InsertAfter,
}))
{ %>
它工作正常,返回的视图被附加到 div,但是我现在需要在发布成功时执行 JavaScript,所以我想:“简单,只需将 OnSuccess = "MyJsFunc()"
" 添加到 AjaxOptions
即可,但这样做后,它停止工作了!现在页面已刷新,并且仅呈现返回的部分视图:(,我什至尝试使用简单的 Alert("Hi")
并且它不起作用。我怎样才能让它工作?
(顺便说一句,我认为这可能是 https 的重复://stackoverflow.com/questions/1994754/execute-javascript-after-loading-a-mvc-page-using-ajax-beginrouteform但是这个问题被放弃了,没有答案)
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,
}))
{ %>
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?
(by the way I think this can be a dup of https://stackoverflow.com/questions/1994754/execute-javascript-after-loading-a-mvc-page-using-ajax-beginrouteform but that question got abandoned with no answer)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有什么理由不以正确的方式去做(毕竟我们已经是 2010 年了)?将 MS AJAX 以及依赖于它的所有
Ajax.*
帮助程序转储到它所属的位置并编写正确的代码。虽然在经典 Web 表单中使用 MS AJAX 可能是合理的,因为 UpdatePanel 等,但今天在新的 ASP.NET MVC 应用程序中使用 MS AJAX,尤其是在 Microsoft 完全接受 jQuery 之后,似乎是一个坏主意。因此,在咆哮之后,这是我的建议:
然后在单独的文件中使用 jquery 不显眼地附加提交处理程序:
或使用优秀的 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:
and then attach the submit handler unobtrusively using jquery in a separate file:
or using the excellent jquery form plugin:
Benefits of this approach:
Bonus benefit: no headaches.
我不断环顾四周,在这里找到了答案:
将 Javascript 函数分配给 AjaxOptions OnSuccess 属性会引发错误 - ASP.NET MVC(未选择答案)
引用 阿兹
这对我有用!
I kept looking around and found the answer here:
Assign a Javascript function to AjaxOptions OnSuccess property raise an error - ASP.NET MVC (with the answer that was not selected)
Quoting Atzu
and it worked for me!