4

I'm creating a new project, asp.net mvc3 with Razor, and wanting to turn the LogOn into an 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 the http response with Fiddler, I notice there is no x-requested-with header. So I add

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

That seems to work, but now what I receive back is a Json object, which isn't being parsed and instead Google Chrome is just rendering the Json to screen by sending back an application/json doc. All the scripts are in place.

I've also done 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 a form of my own creation, which works fine using the standard helpers.

What's happening?

Rob
  • 1,297
  • 2
  • 16
  • 30

1 Answers1

8

That's 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 proper scripts inside your page:

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

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

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

Now you can safely throw away all MicrosoftAjax* script references on your page if you had any, they are no longer used.

This being said personally I never used any of the Ajax.* helpers. I always prefer to have control. So 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');
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • yep, they are all there as standard when you create an MVC app these days – Rob Mar 02 '11 at 07:30
  • @Rob Ellis, nope, they aren't. `jquery.unobtrusive-ajax.js` is not included in your page when you create a new application. It is there in the `Scripts` folder but not included meaning that there is nothing out there to AJAXify your `Ajax.BeginForm` helper and because of this it simply sends a normal HTTP request. You should have seen if you used FireBug by the way. – Darin Dimitrov Mar 02 '11 at 07:31
  • 1
    Hi Darin, I've checked and they're all there. I can view the source and click on the javascript file and receive the content of them. I've checked the web.config for the value too, it's there as well. – Rob Mar 02 '11 at 07:32
  • @Rob Ellis, OK, when you use Ajax.BeginForm the unobtrusive helpers won't parse the result automatically to a JSON object in the success callback :-) You will need to do this yourself. Also note that adding a hidden field inside your form with the `X-Requested-With` seems like a horrible hack. Try looking with FireBug if the request is indeed AJAX or you get some javascript error. Fiddler is not good at this as you only see an HTTP request but can't really make the difference. – Darin Dimitrov Mar 02 '11 at 07:35
  • Lol, ok, ok :-) I've written a simple form outside of the login control (I've added the code to my question) which works fine with the ajax helpers. I just can't figure out why the JSON is not being rendered in the LogOn example! – Rob Mar 02 '11 at 07:38
  • I've loaded up Firebug, but there is nothing in the console. When I submit, Firefox asks me to save the page (the application/json) data. I've tried this at work - and the code works fine!! Is there anything on my computer's configuration that could be messing this up? – Rob Mar 03 '11 at 06:31
  • To clarify - I can't get the Ajax.BeginForm to work consistently across Visual Studio installs. The JQuery Form plugin works flawlessly. Ditch Microsoft. – Rob Mar 03 '11 at 09:58
  • Including the `jquery.unobtrusive-ajax.js` did it for me! – GONeale Jun 03 '11 at 12:22