I've a form in which I only have to choose between several entities.
So here is what I've done:
Created a view Model:
public class EntityChooserModel
{
public IEnumerable<Entity> AvailableEntities { get; set; }
public int SelectedId;
}
I've two actions in the controller, one with [HTTPPost], one without. In both I have a "SessionUserData", which is session data, bound through data model binding.
[Authorize]
public ActionResult EntityChooser(SessionUserData sessionData)
{
List<Entity> entities = _userStore.GetRoles(User.Identity.Name).Select(ur => ur.Entity).ToList();
Entity entity = sessionData.IdCurrentEntity != null ? entities.Where(e => e.Id == sessionData.IdCurrentEntity).First() : entities.First();
return View(new EntityChooserModel() { SelectedId = entity.Id, AvailableEntities = entities });
}
.
[Authorize]
[HttpPost]
public ActionResult EntityChooser( EntityChooserModel model, SessionUserData sessionData, String returnUrl)
{
if (ModelState.IsValid)
{
Entity entity = _userStore.GetRoles(User.Identity.Name).Select(ur => ur.Entity).Where(e => e.Id == model.SelectedId).First();
sessionData.IdCurrentEntity = entity.Id;
RedirectToDefaultPage(returnUrl);
}
return View(model);
}
And the strongly typed view:
@model My.Full.Namespace.EntityChooserModel
@{
ViewBag.Title = "EntityChooser";
Layout = "~/Views/Shared/_LoginLayout.cshtml";
}
<div id="login-wrapper">
<div id="title">
<h1>Login</h1>
</div>
<div id="login">
@using (Html.BeginForm("EntityChooser", "Auth", FormMethod.Post, new { id = "ChooseFormId" }))
{
@Html.ValidationSummary(true, "Loggin error")
<div>
<span>Choose an entity:</span>
@Html.DropDownListFor(x => x.SelectedId, new SelectList(Model.AvailableEntities, "Id", "Name"))
</div>
<p class="right-aligned">
<a href="javascript:document.getElementById('ChooseFormId').submit();" class="adm-button">
<span class="next-btn"><span>Select</span></span></a>
</p>
<input type="submit" style="display: none" />
}
</div>
</div>
The problem is that when I receive the data in the second model, I've an empty object. The collection is empty, and the id is set to the default value(0).
What is wrong? I can't find out what I missed on this one.
It's the first time I do an mvc form which isn't ForModel(), and the first time I've to use a dropdownlist