I have a form in which I need to choose between only a few objects.
So here is what I did:
View model created:
public class EntityChooserModel { public IEnumerable<Entity> AvailableEntities { get; set; } public int SelectedId; }
I have two actions in the controller, one with [HTTPPost], one without. I have a "SessionUserData", which is the session data associated with 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 a 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 get data in the second model, I have an empty object. The collection is empty and the identifier is set to the default value (0).
What's wrong? I canβt find out what I missed on this one.
This is the first time I am making an mvc form that is not ForModel() , and the first time I should use a dropdown