BigBadVoodoo
BigBadVoodoo

Reputation: 23

Ajax.BeginForm() not working asynchronously

I'm trying to learn ASP.Net MVC and i'm having trouble getting Ajax.BeginForm to update a partial view asynchronously. This is the code in the view for the action:

@using (Ajax.BeginForm(
            new AjaxOptions
            {
                HttpMethod = "get",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "restaurantList"
            }))

{
    <input type="search" name="searchTerm" />
    <input type="submit" value="Search By Name." />
}

@Html.Partial("_Restaurants", Model)

The check for an ajax request in the action always returns false and the entire screen is updated rather then just the partial view. It looks like this:

if (Request.IsAjaxRequest())
            {
                return PartialView("_Restaurants", model);
            }

            return View(model);

I'm including a bunch of jquery script files in the BundleConfig.

bundles.Add(new ScriptBundle("~/bundles/otf").Include(
                "~/Scripts/jquery-{version}.js",
                "~/Scripts/jquery-ui-{version}.js",
                "~/Scripts/jquery.unobtrusive*",
                "~/Scripts/jquery.validate*",
                "~/Scripts/jquery-migrate-{version}.js",));

I'm calling the render function right before the end of the body section in a shared layout view that is used by all views in my project

@Scripts.Render("~/bundles/otf")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>

I've been trying to solve this for 2 days but i'm getting nowhere. Any help would be greatly appreciated!

Upvotes: 2

Views: 1401

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Make sure that the jquery.unobtrusive-ajax.js script is present in your Scripts folder and fetched in a <script> tag.

If it isn't make sure you have installed the Microsoft.jQuery.Unobtrusive.Ajax NuGet in your project which will add this script to the Scripts folder of you application.

I have noticed that with Visual Studio 2015 when creating a new ASP.NET MVC application this script isn't present out of the box and I had to install this NuGet in order to have it available. I don't know the reason of this script being removed in the latest MVC version - maybe it's deprecated and now there's an alternative way to achieve that but it's been a long time since I've been doing some MVC development and I am not quite sure what is the recommended way now.

Upvotes: 2

Related Questions