Reputation: 1735
I am currently developing a .net mvc 3 application. Here is the problem. For some reason, Though I am using Ajax.BeginForm and the right action is getting called, after the action completes, it is trying to redirect as if to another page that does not exist. However, I want it to stay on the same page just submit the form using ajax and return some friendly message to the user after the action completes.
Here is my Ajax.BeginForm page:
@using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "Post" }))
{
<div id="lnkContainer"><a href="#" onclick="javascript:document.forms[0].submit(); return false;">Update</a> </div>
@Html.TextAreaFor(m => m.Message, new { style = "width:575px" })
}
Here is my Action:
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public PartialViewResult Action(ActionModel actionModel)
{
database-related code
.....
database-related code
return PartialView();
}
Upvotes: 4
Views: 1356
Reputation: 333
I faced the same problem, I solved it by adding the below code in the BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
and then the below code in _Layout.cshtml
@Scripts.Render("~/bundles/jqueryajax")
Upvotes: 0
Reputation: 1717
I'm fairly certain your problem lies in onclick="javascript:document.forms[0].submit();"
. This will submit the form as a normal POST request. If you want to use the @Ajax.BeginForm
helper, use a regular <input type="submit">
to trigger the submit. If you really need to use a link, then using @Ajax.BeginForm
really doesn't matter because you will have to code submitting an Ajax request using jQuery, etc.
As far as Ajax.BeginForm
and redirection is concerned, the form will revert to a normal HTML form in the event that the user has disabled javascript in their browser, or if your missing the appropriate scripts, etc.
Upvotes: 1