2

when i am using Request.IsAjaxRequest(). i am not able to return view(). please check below code. this is Action.

public ActionResult Index()
    {
        if (!Request.IsAjaxRequest()) {
            return View("ajexview");            
        }
        return view("About");
    }

this is view

<script>
$(function () {
    $("button").click(function () {
        var car = { Make: 'Audi', Model: 'A4 Avant', Color: 'Black', Registered: 2013 };
        $.ajax({
            type: "POST",
            url: "/home/index/",
            data: car,
            datatype: "html",
            success: function (data) {
                $('#result').html(data);
            }
        });
    });
});

<button>Click me</button>

when i am posting about view is not able to return

sp00m
  • 47,968
  • 31
  • 142
  • 252
jitendra rathore
  • 236
  • 1
  • 2
  • 7
  • You should use another action in your controller to handle ajax requests. Normally, when you make ajax request, you point it to an action returning something like `JsonResult`. Take a look to the controller code of this question: http://stackoverflow.com/questions/16186083/making-a-simple-ajax-call-to-controller-in-asp-net-mvc – ADreNaLiNe-DJ Mar 16 '16 at 08:08

2 Answers2

0

First off, i'm not sure if your Index action will be hit by your ajax call at all. You are doing a post against a get action. To get the Request.IsAjaxRequest() to work as intended, either try creating another controller action and marking it with the HttpPost attribute like so,

[HttpPost]
public ActionResult Index(Car car)
{
   if (!Request.IsAjaxRequest()) {
        return PartialView("ajexview");            
    }
    return View("About");
}

Note also that in the if (!Request.IsAjaxRequest()) block i'm returning "ajexview" as a PartialView.

or if your intention was to hit the get Index action then you will need to do an ajax 'get' request instead like

$.ajax({
        type: "GET",
        url: "/home/index/",
        success: function (data) {
        $('#result').html(data);
    }
});
Chico Bell
  • 1
  • 1
  • 1
0

Be sure to Render scripts in the right place and order in your _layout.cshtml:

e.g. at the top: ...

    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>

... and the bottom:

         @Scripts.Render("~/bundles/jquery")
         @Scripts.Render("~/bundles/jqueryval")
         @Scripts.Render("~/bundles/bootstrap")
         @Styles.Render("~/Content/datatables")
         @Scripts.Render("~/bundles/datatables")
         <!-- etc. -->
         @RenderSection("scripts", required: false) 
    </body> 
</html>

Also be mindful of the construction of your BundleConfig.cs.

GPBFNQ
  • 1
  • 2