我有以下代码发布到我的控制器中的httppost方法:
$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);
}
}
});
});
问题是,如果他们没有输入$QuickEmail
或$QuickPassword
字段中的任何内容,则ajax调用会返回以下错误:
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>
但如果填写了两个字段,我的ajax方法调用工作正常。这是我的httppost方法:
[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);
}
答案 0 :(得分:2)
问题在于操作代码的最后一行。
您实际上没有名为 LogOnAjax 的视图。所以,你应该使用
return RedirectToAction(YOUR_LOGON_ACTION_NAME);
或者让你的模型回到表格,你可以使用
return View(YOUR_LOGON_VIEW_NAME, model);
得到你想要的东西。
此外,如果要在所有情况下返回json对象,最好使用 JsonResult 。
答案 1 :(得分:0)
好像你没有名为“LogOnAjax”的相关视图。因为你期待JSON响应,你可以做的就是改变这样的return语句。
// If we got this far, something failed, redisplay form
return Json("Please enter valid username and password");
}