ViewModel值始终为null

时间:2016-05-17 18:26:50

标签: c# asp.net asp.net-mvc asp.net-mvc-5 viewmodel

我已经遵循了一些教程,而且我也在搜索StackOverflow,但我仍然处于死胡同。

基本上,我试图在MVC 5中提交一个表单(MVC的新版本,尽管使用了大量的WebForms)。所以这是我的组件 -

控制器(./Controllers/AccountController.cs)

using BitHost.Models;
using System.Web.Mvc;

namespace BitHost.Controllers
{
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(UserAccount model)
        {
            string sEmailAddress = model.EmailAddress;
            string sPassword = model.Password;
            bool bAgreedToTerms = model.AgreedToTerms;

            return Redirect("/");
        }
    }
}

ViewModel(./ Models/AccountModel.cs)

namespace BitHost.Models
{
    public class UserAccount
    {
        public string EmailAddress;
        public string Password;
        public bool AgreedToTerms;
    }
}

查看(./Views/Account/Register.cshtml)

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Register";
}

@model BitHost.Models.UserAccount

<div class="row">
    <h2>Create a new account</h2>
    @using (Html.BeginForm())
    {
        <div class="input-group">
            <span class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></span>
            @Html.TextBoxFor(model => model.EmailAddress, new { Class = "form-control", Placeholder = "Email Address" })
        </div><br />
        <div class="input-group">
            <span class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></span>
            @Html.TextBoxFor(model => model.Password, new { Class = "form-control", Type = "password", Placeholder = "Password" })
        </div><br />
        <div class="input-group">
            <span class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></span>
            <input type="password" class="form-control" placeholder="Verify Password" />
        </div><br />
        <div class="input-group">
            @Html.CheckBoxFor(model => model.AgreedToTerms, new { Class = "form-control" })
        </div><br />

        <input type="submit" name="Submit" class="btn btn-default" />
    }
</div>

点击&#34;提交&#34;在注册表单上,我确实接受了[HttpPost]操作来创建帐户,但是从模型收集的变量都包含空值。

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:5)

UserAccount不正确。像这样编辑

UserAccount