ASP.NET 5/MVC 6 Ajax 将模型发布到控制器 [英] ASP.NET 5 / MVC 6 Ajax post Model to Controller

查看:14
本文介绍了ASP.NET 5/MVC 6 Ajax 将模型发布到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 ASP.NET 5 MVC 6 应用程序中,我想使用 Ajax 将一些数据发布到我的控制器.我已经用 ASP.NET MVC 5 完成了这项工作,并在一个空白的 ASP.NET MVC 5 项目中测试了完全相同的代码并且它可以工作,但是对于新版本我不能,我不知道为什么.通过 Ajax 调用,我可以转到控制器,创建模型但字段为空(或布尔值为假).这是我的代码:

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:

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; }
}

有什么想法吗?谢谢

推荐答案

如果你使用的是json,你需要在MVC6上显式使用FromBody

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:

内容类型必须是:application/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
};

这是您在检查请求(通过 chrome 调试器工具 F12)或使用请求检查器(如 fiddler)时应该看到的内容.

this is what you should see when inspecting the request (via chrome debugger tools F12) or using a request inspector like fiddler.

如果您看到 UserName=Test&Password=Test&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.

您不需要 model 变量.如果您看到您的请求带有包装",那么您应该将其删除.

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 Ajax 将模型发布到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆