Ajax.BeginForm routing to new page instead of a partial view
Asked Answered
U

1

6

I have a Ajax.BeginForm call that is supposed to return a partial view but is rerouting the page to the Action instead. Any ideas on what is wrong?

Here is the code on the main page that I want to render the partial view on:

    <div class="col-md-6">
        @using (Ajax.BeginForm("Search", "Home", new AjaxOptions
        {
            HttpMethod = "GET",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "searchResults"
        }))
        {

        <div class="form-group" style="width:85%;">
            <div class="right-inner-addon">
                <i class=" glyphicon glyphicon-search"></i>
                <input type="text" data-autocomplete="@Url.Action("Quicksearch","Home")" class="form-control" placeholder="Search" name="q" />
            </div>
        </div>
        <div class="form-group">
            <button class="btn btn-default form-inline" type="submit">Search</button>
        </div>
        }
        <br />

    </div>

</div>
<div id="searchResults">

</div>

Here is the Partial view (items removed due to length):

    <div class="row" id="searchResults">
     ...removed form elements
       <div class="row">
            <table class="table">
    ....stuff
    </table>
    </div>
</div>

Here is the controller:

   public PartialViewResult Search(string q)
    {
        var items = db.items_with_descriptions
            .Where(r => r.name.Contains(q) || string.IsNullOrEmpty(q))
            .Take(10);
        return PartialView("_Items", items);
    }

As stated above, when I click my search button it redirects to localhost:24942/Home/Search instead of staying on the page and simply loading the partial view. I am new to MVC, so please keep that in mind. :)

Uranalysis answered 4/5, 2014 at 18:47 Comment(2)
Is the jquery-unobtrusive js file included in your page? If it isnt, you normally get the behavior that you're describingLiterator
I just discovered that issue myself actually. :) I was missing the js file. If you post an answer I will give you credit.Uranalysis
L
10

The jquery-unobtrusive js file has to be included in your page to make the ajax.beginform work

Literator answered 4/5, 2014 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.