I’m trying to populate a dropdownlist with a list of value that sometimes may come in with a selected value. My problem is that it gives me this error:
The ViewData item that has the key 'ModuleID' is of type 'System.Guid' but must be of type 'IEnumerable<SelectListItem>'.
humble-appre...
Member
32 Points
73 Posts
DropDownList not working
May 06, 2012 04:53 PM|LINK
Hello!
I’m trying to populate a dropdownlist with a list of value that sometimes may come in with a selected value. My problem is that it gives me this error:
The ViewData item that has the key 'ModuleID' is of type 'System.Guid' but must be of type 'IEnumerable<SelectListItem>'.
This is my view:
<div class="editor-label">
@Html.LabelFor(model => model.ModuleID, "Module")
</div>
<div class="editor-field">
@Html.DropDownList("ModuleID", "Please select")
@Html.ValidationMessageFor(model => model.ModuleID)
</div>
This is my Controller with the Action and method to populate the list:
void PopulateModuleList(Guid selectedModule)
{
List<Module> modules = SecurityModuleViewModelBuilder.ConvertToModules(repository.GetModules(true));
Module module = modules.Find(m => m.ID == selectedModule);
ViewBag.ModuleID = new SelectList(modules, "ID", "Name", module);
}
public ActionResult CreateTask(Guid? id)
{
Task task = new Task();
if (id.HasValue && id.Value != Guid.Empty)
PopulateModuleList(id.Value);
return View(task);
}
The behaviour I’m looking for is that when an GUID is past that value comes in as selected on the view and when it is not, display “Please select”.
Thanks!
humble-apprentice
ignatandrei
All-Star
137645 Points
22141 Posts
Moderator
MVP
Re: DropDownList not working
May 06, 2012 05:15 PM|LINK
Where do you populate with System.Guid ? please show all code!
humble-appre...
Member
32 Points
73 Posts
Re: DropDownList not working
May 07, 2012 12:15 PM|LINK
ModuleID is a property of Task of type Guid.
This is how I solved the issue:
void PopulateModuleList(Guid selectedModule) { List<Module> modules = SecurityModuleViewModelBuilder.ConvertToModules(repository.GetModules(true)); if (selectedModule != Guid.Empty) ViewBag.ModuleID = new SelectList(modules, "ID", "Name", selectedModule); else ViewBag.ModuleID = new SelectList(modules, "ID", "Name"); } public ActionResult CreateTask(Guid? id) { Task task = new Task(); if (id.HasValue && id.Value != Guid.Empty) PopulateModuleList(id.Value); else PopulateModuleList(Guid.Empty); return View(task); }This code populates the dropdown, if an ID is passed it is set as selected and if not it just displays the list.
humble-apprentice