我跟着一些教程,我也搜刮了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]操作來創建帳戶,但是這些變量從所有包含空值模型蒐集。
任何幫助將不勝感激,謝謝。
我不知道爲什麼它張貼空值,但是你想改變你的htmlAttributes參數爲小寫,例如'new {@class =「form-control」,type =「password」,placeholder =「Password」}' – jrummell
可能發佈null值,因爲在你的控制器中你沒有保存任何東西?你正在初始化,然後立即說'返回重定向'。 –
@AgustinMeriles他的動作方法可以被命名爲相同的,因爲他的第一個'Register ActionResult'是'HttpGet',另一個'Register ActionResult'是'HttpPost'。 –