【问题标题】:Why is Model Binding not working in my POST action method?为什么模型绑定在我的 POST 操作方法中不起作用?
【发布时间】:2015-08-19 07:48:17
【问题描述】:

我对 MVC 有一个非常奇怪的问题。 我的模型一直被提交为空。 这可能真的很简单,但我就是找不到问题。

我的模型如下所示:

public class LoginModel
{
   public string Username;
   public string Password;
}

我的控制器是这样的:

[HttpGet]
public ActionResult Login()
{
     return View();
}

[HttpPost]
public ActionResult Login(LoginModel loginTest)
{
      if (loginTest.Username != "x" && loginTest.Password != "y")
      {
           ModelState.AddModelError("a", "Login failed.");
           return View(loginTest);
      }
      else
      {
         return RedirectToAction("Home", "Welcome");
       }

}

而且视图也很简单,像这样。

@model LoginSolution.Models.LoginModel
@{
   Layout = null;
}
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Login</title>
    </head>
    <body>
        @using (Html.BeginForm("Login", "Home")) 
        { 
        <div> <span>Username : </span>
            @Html.EditorFor(model => model.Username)
        <br />
            <span>Password : </span>
            @Html.EditorFor(model => model.Password)
        <br />
        @Html.ValidationSummary()
        <br />
        <input type="submit" value="Login" name="Login" />
        </div>
        }
    </body>
    </html>

这不是关于安全或最佳实践的问题。 这只是一个关于为什么模型在提交时总是将自身返回为空的问题。

【问题讨论】:

  • 首先使用chrome inspect elemnt,捕获使用network tab发送的表单。
  • 我也有同样的问题。即使在添加 getter/setter 模型后也不起作用。我总是在 POST 中得到空对象。我在 web.config 中有 authentication mode="Forms"

标签: asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

您的模型包含字段,而不是属性(没有 getter/setter),因此模型绑定器无法设置值。将您的模型更改为

public class LoginModel
{
   public string Username { get; set; }
   public string Password { get; set; }
}

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2023-04-09
    • 1970-01-01
    • 2016-01-11
    • 2019-07-18
    • 2022-12-07
    • 1970-01-01
    • 2020-01-13
    • 2022-01-11
    相关资源
    最近更新 更多