如何使用Ajax.BeginForm OnSuccess和OnFailure方法?

我使用这个Ajax.BeginForm

  

我需要在控制器中写一下这个OnSucces和OnFailure。

因为OnSuccess我需要显示Success消息

OnFailure我需要显示其他消息。

在我的控制器中

 Public ActionResult GetSomething(FromCollection collection) { if(exists == null) { //OnSuccess } else { //OnFailure } } 

anydboy可以帮帮我..怎么抓住这个?

谢谢

OnSuccess和OnFailure看起来像是期待javascript回调函数。

  <%= Ajax.ActionLink("Click me", "MyAction", new AjaxOptions { UpdateTargetId = "myElement", OnFailure = "handleError"}) %> 

Pro ASP.NET Framework第425页的示例

ASP.NET AjaxOptions类


添加控制器示例

最简单的方法是我在这里得到的,但我建议使用某种ViewModel查看强类型的mvc视图,并考虑使用jQuery为你的ajax。 有了这个说,这应该有希望对你有用。

 if (exists) { ViewData["msg"] = "Some Success Message"; } else { ViewData["msg"] = "Some Error Message"; } return View(); 

在你看来

 
<%: ViewData["msg"]%>

我也在寻找相同的答案,但看起来像Ajax.BeginForm()..的事件没有很好的记录或需要更多的自我实验来找出何时调用这些onSuccess和onFailure事件。 但是我有一个非常简单直接的替代方案,不用担心设置AjaxOptions的onSuccess和onFailure属性。 相反,在Controller的action方法中,只需通过将ActionResult作为JavaScriptResult发送来调用onSuccess(),onFailure()javascript方法。 例如,

 Public ActionResult Create(FromCollection collection) { if(exists == null) { //OnSuccess return JavaScript("OnSuccess();"); } else { //OnFailure return JavaScript("OnFailure();"); } } 

而Ajax.BeginForm标签应该是这样的

  <% using( Ajax.BeginForm( "Create","Mandate", new AjaxOptions())) // see, no OnSuccess and OnFailure here. {%> <% } %> 

现在,您需要在页面中定义OnSuccess()和OnFailure()javascript方法,这就是它。

编辑:

我想,如果没有从服务器抛出exception,默认情况下会调用OnSuccess()。 如果从服务器抛出任何exception,将调用OnFailure()。 我还没有测试这个概念。 如果这是真的,那么练习发送JavaScript(“OnSuccess();”)和JavaScript(“OnFailure();”)并不是一个好主意; 来自服务器,因为这不是一个好的模式。