Chr*_*gax 26 c# ajax asp.net-core-mvc asp.net-core
在我的ASP.NET 5 MVC 6应用程序中,我想向Ajax发布一些数据到我的控制器.我已经使用ASP.NET MVC 5完成了这项工作,我在一个空白的ASP.NET MVC 5项目中测试了完全相同的代码并且它可以工作,但是新版本我不能,我不知道为什么.通过Ajax调用,我可以转到控制器,创建模型但字段为空(或布尔值为false).这是我的代码:
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:
[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:
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; }
}
有任何想法吗 ?谢谢
Bar*_*xto 30
如果使用json,则需要在MVC6上明确使用FromBody
public JsonResult Login([FromBody]LoginViewModel model)
编辑
我认为你混合了不同的错误.我将尝试描述您应该如何提出请求:
content-type 必须是:application/json
您的请求正文必须是 JSON格式(如JasonLind所建议):
{
    UserName: 'Test',
    Password: 'Test',
    RememberMe: true
};
这是您在检查请求时(通过chrome调试器工具F12)或使用fiddler等请求检查器时应该看到的内容.
如果你看到某种形式的东西UserName=Test&Password=Test&RememberMe=true那么你做错了,这就是表格格式.
你不需要model变量.如果您使用"包装器"看到您的请求,则应将其删除.
| 归档时间: | 
 | 
| 查看次数: | 40077 次 | 
| 最近记录: |