Why doesn't Request.IsAjaxRequest () work in ASP.NET MVC 3?

I am creating a new asp.net mvc3 project with Razor and want to turn LogOn into ajax request.

HTML

@using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions { HttpMethod="post", OnSuccess="LoginSubmitted"})) { } 

controller

 if (Request.IsAjaxRequest()) { return Json(new { ResultMessage = "Username or password provided is incorrect"}); } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } 

Everything else remains the same.

First, looking at the http response from Fiddler, I notice that the header with the request x is missing. Therefore i add

 <input type="hidden" name="X-Requested-With" value="XMLHttpRequest" /> 

This seems to work, but now what I get is a Json object that is not parsed, and instead Google Chrome just displays Json on the screen, sending back the / json doc application. All scripts are in place.

I also did this:

 @using (Ajax.BeginForm("Submit", "home", new AjaxOptions { HttpMethod = "Post", OnSuccess="LoginSubmitted"})) { } @section head { <script type="text/javascript"> function LoginSubmitted(res) { alert(res.Message); } </script> } public ActionResult Submit(string id) { if (Request.IsAjaxRequest()) { return Json(new { Message = "Logged In" } ); } else { return View(); } } 

In the form of my own creation, which works great with standard helpers.

What's happening?

+4
source share
1 answer

This is because by default ASP.NET MVC 3 uses jQuery and unobtrusive AJAX instead of the MicrosoftAjax * library. This means that when you write Ajax.BeginForm , you will need to include the correct scripts inside your page:

 <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script> 

and in your web.config make sure you have unobtrusive javascript:

 <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 

Now you can safely throw all the MicrosoftAjax* script links to your page, if you have them, they are no longer used.

That being said, I have never used any of the Ajax.* . I always prefer to have control. Therefore, I would write:

 @using (Html.BeginForm("LogOn", "Account")) { } 

and then AJAXify this form using the jquery form plugin:

 $(function() { $('form').ajaxForm(function(result) { alert('form successfully submitted'); }); }); 
+8
source

Source: https://habr.com/ru/post/1341940/


All Articles