I have a problem with Ajax.BeginForm. I have a form with submit and button that updates partial view.
What I am trying to accomplish is that I could use following return statements in the same Action.
// button activates this
return PartialView("PartialViewName", data);
and
// submit activates this
return Redirect(model.Url);
Now the problem is that Redirect causes problems to the Ajax.BeginForm
<% using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { OnSuccess = "OnSuccess", UpdateTargetId = "Container", InsertionMode = InsertionMode.Replace }, new { id = "eventAjaxForm" })) { %>
How can I identify is the result PartialView or are we redirecting user?
Normally when you perform an AJAX call to a controller action any redirects are followed until the client gets 200 status code or an error. So the HTML of the url you are redirecting to will be placed in the Container
div. On the other hand in your controller action you could test whether the call was asynchronous using Request.IsAjaxRequest()
and return a partial.
If you are using the Post Redirect Get pattern, you will need to use Request.IsAjaxRequest() in conjunction with TempData, ie, you persist the result of Request.IsAjaxRequest() in TempData, that way, when you get the redirected request, you can check TempData to see if it is the result of an original Ajax request.
This is explained well in Steven Sandersons book on Pro ASP.NET MVC 2.
Thank you guys for your answers, but I was able to solve the problem with other solution.
I made separate action for the submit and for the partial view. Partial view update is done with following jQuery method.
$('.class').click(function () {
var form = $("#eventForm").serialize();
$.post("/Controller/Action",
{
form
},
function (result) {
$('#container').html(result);
}
);
});
and submit is done with "normal" submit button.