执行发布时没有数据

时间:2015-12-01 19:23:23

标签: c# asp.net-mvc

AccountController.cs

namespace IndividueleOpdracht.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Login()
        {
            return View(new Account());
        }

        [HttpPost]
        public ActionResult Login(Account model)
        {
            if (!ModelState.IsValid) return View();

            if (model.Login())
            {
                return RedirectToAction("Index", "News");
            }

            return View();
        }
    }
}

Account.cs

namespace IndividueleOpdracht.Models
{
    public class Account
    {
        [Required]
        public string Email;

        [Required]
        public string Password;

        public bool Login()
        {
            if (Email == "test" && Password == "test")
            {
            return true;
            }

            return false;
        }
    }
}

Login.cshtml

@model IndividueleOpdracht.Models.Account

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-signin" }))
{
    <h2 class="form-signin-heading">Login</h2>
    <label for="inputEmail" class="sr-only">Email address</label>
    @Html.TextBoxFor(model => model.Email, new { @type = "email", @id = "inputEmail", @class = "form-control", @placeholder = "Email adres" })
    <label for="inputPassword" class="sr-only">Wachtwoord</label>
    @Html.PasswordFor(model => model.Password, new { @id = "inputPassword", @class = "form-control", @placeholder = "Wachtwoord" })
    <div class="checkbox">
        <label>
            <input type="checkbox" value="remember-me"> Onthoud mij
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
}

当我发帖时,它说模型参数为空。电子邮件为空,密码也是。

ModelState.IsValid为true。

有人可以告诉我我做错了什么。

由于

1 个答案:

答案 0 :(得分:2)

将您的视图模型类更改为设置/获取并将其设为公共属性。

public class Account
{
    [Required]
    public string Email {set;get;};

    [Required]
    public string Password {set;get;};

}

如果您不将它们保留为属性(使用set),则MVC模型绑定器在从已发布的表单数据中读取后无法将值设置为这些属性。

另外,要查看验证摘要,您可以使用Html.ValidationSummary()方法。因此,当模型验证失败时,您将看到属性验证错误列表。

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    @Html.TextBoxFor(s=>s.Email)
    <input type="submit" />
}