I'm having problems using Ajax.BeginForm()
in my simple ASP.NET MVC application. I've searched SO for solution but nothing I found seems to help.
I've created a new project using the default Visual Studio 2015 template. I've changed the Index.cshtml
file to:
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div id="ajax-test"></div>
@using (Ajax.BeginForm("Test", new AjaxOptions()
{
UpdateTargetId = "ajax-test",
InsertionMode = InsertionMode.Replace
}))
{
<input type="submit" />
}
</div>
I've added a new action to HomeController
:
public ActionResult Test()
{
return PartialView("Test");
}
A new view Home\Test.cshtml
:
Hello world
And, crucially, I've added a reference to the required JavaScript files to _Layout.cshtml
(moving them to the top of the page doesn't help).
...
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
I've verified the jqueryval
bundle renders in the debug mode as:
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
These entries were already present in web.config
file:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
I would expect that when I press Submit, the div will be populated with 'Hello world'. Instead, the whole page is replaced with 'Hello world' and the browser is redirected to /Home/Test
. No errors reported in developer tools.
What element of the puzzle is missing? I know similar questions have been asked on StackOverflow before but the usual answer was to include these JavaScript files, which I did. Above are all the changes I've done to the template project so I can't see what I could break.
I've struggled with it for hours and managed to find the solution 5min after posting on StackOverflow. Typical.
I had to install a NuGet package Microsoft.jQuery.Unobrusive.Ajax
, which is not installed by default, and add a reference to jquery.unobtrusive-ajax.js
to the page. I thought it has been merged in into jquery.validate.unobtrusive.js
or something but no.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With