Question

How do I pass a view model and another parameter to my action method using jquery ajax?

with what I'm doing now, the action method is not being called. I think the cause is probably because the parameters are not being passed correctly in the data object of the jquery ajax call:

jQuery ajax:

$('#form-login').submit(function (event) {
                event.preventDefault();

                $.ajax({
                    url: "/Account/LogOn/",
                    data: $('#form-login').serialize(),
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        if (data.userAuthenticated) {
                            window.location.href = data.url;
                        } else {
                            formBlock.clearMessages();
                            displayError($('#errorcred').val());
                        }
                    },
                    error: function () {
                        formBlock.clearMessages();
                        displayError($('#errorserver').val());
                    }
                });
        });

Action method (which accepts the view model and another parameter):

[HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        // Validate the email and password
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(model.UserName, model.Password))
            {
                FormsService.SignIn(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    if (Request.IsAjaxRequest())
                    {
                        return Json(new { userAuthenticated = true, url = returnUrl, isRedirect = true });
                    }
                    else
                    {
                        return Redirect(returnUrl);
                    }
                }
                else
                {
                    if (Request.IsAjaxRequest())
                    {
                        return Json(new { userAuthenticated = true, url = Url.Action("Index", "Home"), isRedirect = true });
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            } 
        }
        else
        {
            if (Request.IsAjaxRequest())
            {
                return Json(new { userAuthenticated = false, url = Url.Action("LogOn", "Account") });
            }
            else
            {
                ModelState.AddModelError("", adm.ErrorUserNamePassword);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
Was it helpful?

Solution

Remove the following from the $.ajax call:

contentType: 'application/json; charset=utf-8',

You have specified application/json encoding but the $('#form-login').serialize() function is sending application/x-www-form-urlencoded content.

As far as sending the returnUrl parameter is concerned, you could simply read it from the form action where it should be present (if you used the Html.BeginForm() helper):

$.ajax({
    url: this.action,
    ...
});

Also you probably want to rename the event variable with something else as this is a reserved word in javascript:

$('#form-login').submit(function (e) {
    e.preventDefault();

    ...
});

OTHER TIPS

The only way I have found to do this is to just include the second parameter in your viewmodel and continue to serialize your form the way you are doing now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top