I using this Ajax.BeginForm
<% using( Ajax.BeginForm( "Create","Mandate",
new AjaxOptions( ) {
OnSuccess = "GoToMandates",
OnFailure = "ShowPopUpError"
} ) ) {%>
<% } %>
What do I need to write in the controler to catch this OnSucces and OnFailure.
Because OnSuccess I need to show Success message
OnFailure I need to show othere message.
In my Controller
Public ActionResult GetSomething(FromCollection collection)
{
if(exists == null)
{
//OnSuccess
}
else
{
//OnFailure
}
}
Can anydboy help me out.. how to catch this?
Thanks
The OnSuccess and OnFailure looks like they are expecting javascript callback functions.
<script type="text/javascript">
function handleError(ajaxContext) {
var response = ajaxContext.get_response();
var statusCode = response.get_statusCode();
alert("Sorry, the request failed with status code " + statusCode);
}
</script>
<%= Ajax.ActionLink("Click me", "MyAction",
new AjaxOptions { UpdateTargetId = "myElement", OnFailure = "handleError"}) %>
Example from Pro ASP.NET Framework page 425
Added Controller Example
The simpliest way to do this would be what I've got here but I recommend looking into strongly typed mvc views using some kind of ViewModel and maybe look into using jQuery for your ajax. With that said this should hopefully work for you.
if (exists)
{
ViewData["msg"] = "Some Success Message";
}
else
{
ViewData["msg"] = "Some Error Message";
}
return View();
In your view
<div id="myResults" style="border: 2px dotted red; padding: .5em;">
<%: ViewData["msg"]%>
</div>
I was also searching for the same answer, but looks like Ajax.BeginForm() .. 's event's are not well documented or need more self experiments to find out when these onSuccess and onFailure events are called. But I got a very easy and straight forward alternative for not to bother with setting onSuccess and onFailure properties of the AjaxOptions. Rather, in your Controller's action method, simply call the onSuccess(), onFailure() javascript method by sending ActionResult as JavaScriptResult. For example,
Public ActionResult Create(FromCollection collection)
{
if(exists == null)
{
//OnSuccess
return JavaScript("OnSuccess();");
}
else
{
//OnFailure
return JavaScript("OnFailure();");
}
}
And the Ajax.BeginForm tag should look like
<%
using( Ajax.BeginForm( "Create","Mandate", new AjaxOptions())) // see, no OnSuccess and OnFailure here.
{%>
<% } %>
Now, you need to define the OnSuccess() and OnFailure() javascript methods in your page and thats it.
EDIT:
I was thinking, perhaps, OnSuccess() will be called by default if no Exception is thrown from the Server. OnFailure() will be called if any Exception is thrown from the server. I did not test this concept yet. If that is true, then, it wont be a good idea to practice sending JavaScript("OnSuccess();") and JavaScript("OnFailure();"); from the server, because that will not be a good pattern to follow.
来源:https://stackoverflow.com/questions/5517813/how-to-use-ajax-beginform-onsuccess-and-onfailure-methods