hi i'm new to the asp mvc framework, and i've noticed that when i post to a controller it is not binded properly. i was trying to do a save a data to the database, but it was saving a blank data, i don't know why
here's my code for Model:
public int ID { get; set; }
public string UserName { get; set; }
public string UserPass { get; set; }
public UserLevel UserLevel { get; set; }
code for ViewModel:
public List<UserLevel> UserLevels { get; set; }
public User Users { get; set; }
code for Controller:
public ActionResult Index()
{
using (var ctx = new UserContext())
{
var users = ctx.Users.Include(u => u.UserLevel).ToList();
return View(users);
}
}
public ActionResult Create()
{
using (var ctx = new UserContext())
{
var userlevel = ctx.UserLevels.ToList();
var vm = new UserViewModel()
{
UserLevels = userlevel
};
return View(vm);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind] User user)
{
using(var ctx = new UserContext())
{
if (ModelState.IsValid)
{
ctx.Users.Add(user);
ctx.SaveChanges();
return RedirectToAction("Index", "Users");
}
else
{
return new EmptyResult();
}
}
}
here's the view code:
@using (Html.BeginForm("Create", "Users"))
{ @Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Users.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Users.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Users.UserName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Users.UserPass, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Users.UserPass, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Users.UserPass, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Users.UserLevel, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Users.UserLevel, new SelectList(Model.UserLevels, "ID", "Name"), "", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Users.UserLevel, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
}
Thanks in advance