I've seen this type of question asked several times, but I can't figure out a correct and clean way to do this. On the post action, my PossibleAnswers property isn't set anymore (normal, as I'm not posting it back). How should I set it again, as the data is coming from the DB? Querying the db again doesn't seem logical to me, although I guess it works. Is there an alternative solution, like caching the list?
Controller
public ActionResult EditFirstCharac()
{
var userId = _userService.GetUserIdFromName(_userName);
var charac = _characService.GetAllUserCharacteristics(userId).ToList().FirstOrDefault(p => p.SelectedAnswer != null);
var vm = new EditCharacViewModel()
{
CharacId = charac.Id,
IsKey = charac.IsKey,
Question = charac.Question.Title,
Weight = charac.Weight,
PossibleAnswers = charac.Question.PossibleAnswers.ToListSelectListItem(p => p.Id.ToString(), p => p.Label).ToList()
};
return View("Edit", vm);
}
[HttpPost]
public ActionResult EditFirstCharac(EditCharacViewModel vm)
{
if (ModelState.IsValid)
{
// OK, save to DB or whatever
}
// KO, PossibleAnswers is empty
return View("Edit", vm);
}
ViewModel
public class EditCharacViewModel
{
public int CharacId { get; set; }
public string Question { get; set; }
[Range(0, 5)]
public int Weight { get; set; }
public bool IsKey { get; set; }
public List<SelectListItem> PossibleAnswers { get; set; }
public string SelectedAnswer { get; set; }
}
View @model Dating.WebSite.ViewModels.Profile.EditCharacViewModel
@using (Html.BeginForm("EditFirstCharac", "Profile"))
{
<div>@Model.Question</div>
@Html.EditorFor(p => p.IsKey)
@Html.EditorFor(p => p.Weight)
@Html.DropDownListFor(p => p.SelectedAnswer, Model.PossibleAnswers)
@Html.HiddenFor(p => p.Question, new { id = "Question" })
@Html.HiddenFor(p => p.CharacId, new { id = "CharacId" })
<input type="submit" />
}