2016-05-17 108 views
0

我跟着一些教程,我也搜刮了StackOverflow,但我仍然處於死衚衕。我試圖在MVC 5中提交一個表單(儘管MVC中使用了新的,但使用WebForms的時候卻很重要)。因此,這裏有我的部件 -ViewModel值始終爲空

控制器(./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("/"); 
     } 
    } 
} 

視圖模型(./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> 

點擊「提交」報名表上後,我得到帶到[HttpPost]操作來創建帳戶,但是這些變量從所有包含空值模型蒐集。

任何幫助將不勝感激,謝謝。

+0

我不知道爲什麼它張貼空值,但是你想改變你的htmlAttributes參數爲小寫,例如'new {@class =「form-control」,type =「password」,placeholder =「Password」}' – jrummell

+0

可能發佈null值,因爲在你的控制器中你沒有保存任何東西?你正在初始化,然後立即說'返回重定向'。 –

+0

@AgustinMeriles他的動作方法可以被命名爲相同的,因爲他的第一個'Register ActionResult'是'HttpGet',另一個'Register ActionResult'是'HttpPost'。 –

回答

6

UserAccount不正確。編輯這樣

UserAccount

+0

我甚至沒有想過'get'和'set'訪問器。固體拾起 –

+0

是的。接得好。我很驚訝我經常看到這件事情完成,但我從來沒有想過要找到它。我覺得我很習慣看到屬性,我的大腦只是在'{get;組;儘管他們不在那裏。 –

+2

@MDDKOz:你現在稱之爲「領域」,「屬性」有一個getter和setter,即使他們只是自動實現。只有屬性有資格被綁定。 –