I use MVC 3 in ASP.Net my web app is design with ViewModel and ViewModel builder.
I use a Builder class to populate some data in a ViewModel. In my case I have a Create View a DropDownList, with this code work fine. My problem is when trying to create an Edit View, I receive this error:
{"The ViewData item that has the key 'CandidateId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'."}
My idea it would be to populate a DropDownList with some value but have pre-selected one as for databse record.
So How to display a DropDownList in a Edit View with selected a value from a DataBase?
VIEW
<div class="editor-label">
@Html.LabelFor(model => model.CandidateId)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.CandidateId, Model.CandidatesList, "None")
</div>
VIEW MODEL
public Nullable<int> CandidateId { get; set; }
public IEnumerable<SelectListItem> CandidatesList;
VIEW MODEL BUILDER
// We are creating the SelectListItem to be added to the ViewModel
eventEditVM.CandidatesList = serviceCandidate.GetCandidates().Select(x => new SelectListItem
{
Text = x.Nominative,
Value = x.CandidateId.ToString()
});
The reason for this error is because in your
[HttpPost]action you forgot to repopulate theCandidatesListproperty on your view model from the database.Don’t forget that only the selected value of the dropdown list is sent to the server when you submit the form. The
CandidatesListcollection property will be null inside your POST controller action because its values were never sent. So if you intend to redisplay the same view you need to initialize this property because your view depends on it.