问题描述
在我的ASP.NET MVC 5 6的应用程序,我要发布使用Ajax的一些数据,我的控制器。我已经做到了这一点与ASP.NET MVC 5和我在一个空白的ASP.NET MVC 5项目测试完全相同的code和它的工作,但随着新的版本,我不能,我不知道为什么。随着Ajax调用,我可以到控制器,创建模型,但字段为空(或假布尔)。这是我的code:
In my ASP.NET 5 MVC 6 application, I want to post with Ajax some data to my controller. I already done this with ASP.NET MVC 5 and I tested the exact same code in an blank ASP.NET MVC 5 project and it worked, but with the new version I can't and I don't know why.With the Ajax call, I can go to the controller, the model is created but the fields are null (or false for the boolean). Here is my code :
的script.js:
script.js :
var data = {
model: {
UserName: 'Test',
Password: 'Test',
RememberMe: true
}
};
$.ajax({
type: "POST",
url: "/Account/Login/",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do something interesting here.
}
});
AccountController.cs:
AccountController.cs :
[HttpPost]
public JsonResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
//var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
//if (result.Succeeded)
//{
// //return RedirectToLocal(returnUrl);
//}
ModelState.AddModelError("", "Identifiant ou mot de passe invalide");
return Json("error-model-wrong");
}
// If we got this far, something failed, redisplay form
return Json("error-mode-not-valid");
}
LoginViewModel.cs:
LoginViewModel.cs :
public class LoginViewModel
{
[Required]
[Display(Name = "UserName")]
[EmailAddress]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
任何想法?谢谢
Any ideas ?Thanks
推荐答案
您需要在MVC6明确使用FromBody如果您正在使用JSON
You need to explicit use FromBody on MVC6 if you are using json
public JsonResult Login([FromBody]LoginViewModel model)
修改
我觉得你混合不同的错误。我会尽力来形容你应该如何提出请求:
I think you are mixing different errors. I will try to describe how you should make the request:
内容类型的必须:应用程序/ JSON
content-type must be: application/json
您请求主体的必须 JSON格式(如JasonLind建议):
your request body must be in JSON format (as JasonLind suggested):
{
UserName: 'Test',
Password: 'Test',
RememberMe: true
};
这是你应该看到检查的要求(通过镀铬调试工具F12)时,或使用一个请求检查就像小提琴手。
this is what you should see when inspecting the request (via chrome debugger tools F12) or using a request inspector like fiddler.
如果你看到一些在用户名=测试与放大器的形式;密码=测试和放大器;了rememberMe = TRUE
,那么你就错了,这是形式的格式
If you see something in the form of UserName=Test&Password=Test&RememberMe=true
then you are doing it wrong, that's form format.
您不需要模式
变量。如果你看到你的要求有一个包装,那么你应该将其删除。
you don't need the model
variable. if you see your request with a "wrapper" then you should remove it.
这篇关于ASP.NET 5 / MVC 6阿贾克斯后模型控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!