MrDKOz MrDKOz - 3 years ago 111
ASP.NET (C#) Question

ViewModel values are always null

I've followed some tutorials and I've also scoured StackOverflow but I'm still coming up at a dead end.

Basically, I'm trying to submit a form in MVC 5 (new to MVC, used WebForms heavily though). So here are my components -

Controller (./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;
}
}


View (./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>




After clicking on "Submit" on the registration form, I do get taken to the [HttpPost] action to create the account, however the variables gathered from the model all contain null values.

Any help would be appreciated, thank you.

Answer Source

UserAccount is not correct. edit it like this

UserAccount

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download