[英]httppost to controller in mvc not working if value in model is blank or null
I have the following code to post to an httppost method in my controller: 我有以下代码发布到我的控制器中的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);
}
}
});
});
The problem is, if they haven't typed in anything in the $QuickEmail
or $QuickPassword
field, the ajax call returns the following error: 问题是,如果他们没有输入
$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>
But if the the two fields are filled out my ajax method call works fine. 但是如果填写了两个字段,我的ajax方法调用工作正常。 Here is my httppost method:
这是我的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);
}
The problem is with the last line of your action code. 问题出在您的操作代码的最后一行。
You actually don't have a view named LogOnAjax . 您实际上没有名为LogOnAjax的视图。 So, you should use
所以,你应该使用
return RedirectToAction(YOUR_LOGON_ACTION_NAME);
or to have your model back to the form, you can use 或者让你的模型回到表格,你可以使用
return View(YOUR_LOGON_VIEW_NAME, model);
to get what you want. 得到你想要的。
Besides, it's better to use JsonResult if you are going to return a json object in all cases. 此外,如果要在所有情况下返回json对象,最好使用JsonResult 。
Seems like you don't have the relevant view called "LogOnAjax".Since you are expecting a JSON response what you can do is to change the return statement like this. 好像你没有名为“LogOnAjax”的相关视图。由于你期待JSON响应,你可以做的就是改变这样的return语句。
// If we got this far, something failed, redisplay form
return Json("Please enter valid username and password");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.