Captain Skyhawk
Captain Skyhawk

Reputation: 3500

Ajax form reloading/returning new page instead of updating

I'm trying my hand and Asp.net MVC 4 and having an issue with an Ajax form returning a whole new page instead of just updating a div.

Here's the razor html code:

<div class="All">
    <div class="Search">
        @using (Ajax.BeginForm( new AjaxOptions { UpdateTargetId = "CurrentSku" } ))
        {
        @Html.Label("Enter Sku:")
        @Html.TextBox("textBox1")
        <input type="submit" value="Find" />
        }
    </div>
    <div id="CurrentSku">
        <span>No Sku selected.</span>
    </div>

and here's the controller:

    public ActionResult Index()
    {
        // Pay no attention to this, just a place holder
        return View( db.xInventoryExt.Take(1) );
    }

    [HttpPost]
    public ActionResult Index(string textBox1)
    {
        if (db.xInventoryExt.Count(a => a.InvtID == textBox1) < 1)
        {
            return Content("Sku not found.", "text/html");
        }

        var ret = db.xInventoryExt.First(b => b.InvtID == textBox1);

        return Content(ret.ToString(), "text/html");
    }

I was reading that this sometimes happens when not including MicrosoftAjax.debug.js but I can't find a copy of that file anywhere.

Upvotes: 1

Views: 1143

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

I was reading that this sometimes happens when not including MicrosoftAjax.debug.js

Actually you need to include the jquery.unobtrusive-ajax.js script. MicrosoftAjax.debug.js was part of older versions of ASP.NET MVC and is completely obsolete now. So basically if you are using ASP.NET MVC 4 and using the default bundles (~/App_Start/BundleConfig.cs), in your _Layout.cshtml you could simply have the following towards the end of the DOM:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@RenderSection("scripts", required: false)

Now your Ajax.* helpers will work and also you would have enabled unobtrusive jQuery validation. This will happen because of the way this ~/bundles/jqueryval bundle is defined:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.unobtrusive*",
            "~/Scripts/jquery.validate*"));

If you are not using bundles then simply include the corresponding scripts in that order:

<script type="text/javascript" src="~/scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>
@RenderSection("scripts", required: false)

Upvotes: 1

Related Questions