I have the following code to post to an httppost method in my controller:
$QuickLoginSubmit.click(function (e) {
e.preventDefault();
var LoginModel = {
'UserName': $QuickEmail.val() == "" ? null : $QuickEmail.val(),
'Password': $QuickPassword.val() == "" ? null : $QuickPassword.val(),
'RememberMe': $QuickRemember.val() == "on" ? true : false
};
$.ajax({
url: '/Account/LogOnAjax',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(LoginModel),
success: function (result) {
if (result == true) {
window.location = "/Dashboard";
} else {
$QuickLoginErrors.text(result);
}
}
});
});
The problem is, if they haven’t typed in anything in the $QuickEmail or $QuickPassword field, the ajax call returns the following error:
The view 'LogOnAjax' or its master was not found or no view engine supports the searched locations. The following locations were searched:<br>~/Views/Account/LogOnAjax.aspx<br>~/Views/Account/LogOnAjax.ascx<br>~/Views/Shared/LogOnAjax.aspx<br>~/Views/Shared/LogOnAjax.ascx<br>~/Views/Account/LogOnAjax.cshtml<br>~/Views/Account/LogOnAjax.vbhtml<br>~/Views/Shared/LogOnAjax.cshtml<br>~/Views/Shared/LogOnAjax.vbhtml</i>
But if the the two fields are filled out my ajax method call works fine. Here is my httppost method:
[HttpPost]
public ActionResult LogOnAjax(LogOnModel model)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return Json(true);
}
else
{
return Json("The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
The problem is with the last line of your action code.
You actually don’t have a view named LogOnAjax. So, you should use
or to have your model back to the form, you can use
to get what you want.
Update:
Besides, it’s better to use JsonResult if you are going to return a json object in all cases.