John John
John John

Reputation: 1

Checking Request.IsAjaxRequest always return false inside my asp.net mvc4

I have the following code inside my controller

public ActionResult Index(string searchTerm=null)
        {   System.Threading.Thread.Sleep(5000);
            var accountdefinition = repository.FindAccountDefinition(searchTerm).ToList();
            if (Request.IsAjaxRequest())
            { return PartialView("_CustomerTable",accountdefinition); }
        return View(accountdefinition);         
        }

But if I call the above action method using an Ajax.beginform,, then the Request.IsAjaxRequest will return false and the partial view will not be returned

@using (Ajax.BeginForm(
new AjaxOptions{
    HttpMethod= "get",
    InsertionMode=InsertionMode.Replace,
    LoadingElementId = "progress",
    UpdateTargetId="customerTable"}))
    {
<div style="float:right">Search <input placeholder="Search by name.." name="searchTerm" type="text"> <input class="btn btn-success" type="submit" value="search" /></div>               

}
<div id = "progress" class="loadingimage">
<img src="~/Content/Ajax-loader-bar.gif" />
</div>

Upvotes: 13

Views: 10960

Answers (3)

afreeland
afreeland

Reputation: 3979

I ran across this issue and wasnt sure what black magic the jquery.unobtrusive-ajax.min.js file was doing but it was not working for me. I was happy when I ran across this post which explains the very simple problem.

The author of the post declared that there is a header that needs to be populated.

X-Requested-With => 'XMLHttpRequest'

For Angular users that find this post I have included a snippet from above post.

var productsApp = angular.module('productsApp', []);

productsApp.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

Upvotes: 4

John John
John John

Reputation: 1

It seems to me that I did not include the jquery.unobtrusive-ajax.min.js

Upvotes: 22

Jaimin
Jaimin

Reputation: 8020

Hi try this and change your view like this hope it's work for you

 @using (Ajax.BeginForm("Index", "controller", null, new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, LoadingElementId = "progress", UpdateTargetId = "customerTable" }))
        {
            <div style="float: right">
                Search
                <input placeholder="Search by name.." name="searchTerm" type="text">
                <input class="btn btn-success" type="submit" value="search" /></div>               

        }

Upvotes: 1

Related Questions