为什么在我的POST操作方法中无法使用模型绑定? [英] Why is Model Binding not working in my POST action method?

查看:106
本文介绍了为什么在我的POST操作方法中无法使用模型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a really wierd issue with MVC. My models keeps getting submitted empty. And it's probably really simple, but I just can't find the issue.

我的模型如下:

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

}

这样的视图也非常简单.

And the view is also very simple, like this.

@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>

这不是有关安全性或最佳实践的问题. 这只是一个问题,为什么模型在提交后仍将自身返回为空.

This is not a question about security or best practice. This is just a question regarding why the model keeps returning itself as empty upon submitting.

推荐答案

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

Your model contains fields, not properties (no getter/setter) so the model binder cannot set the values. Change your model to

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

这篇关于为什么在我的POST操作方法中无法使用模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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