Question

I am wondering perhaps I am trying to achieve the impossible. I have a button on a page that displays a partialview for adding items to another model. This has a dropdownlist which upon further investigation returns null and hence throws up an error:

System.InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'ProjectId'.

I am using a ViewBag.ProjectId in the controller

int userId = (int)MySqlWebSecurity.CurrentUserId;
 ViewBag.ProjectId = new SelectList(db.ProjectDocuments.Where(a=>a.ProjectUserId=userId), "ProjectId", "ProjectTitle");

RenderPartial which should be rendered in modal popup

@{Html.RenderPartial("_AddProjectDocument", new ProjectUno.Models.ProjectDocument());}

in _AddProjectDocument.cshtml

<div class="editor-field">
        @Html.DropDownList("ProjectId", String.Empty)
        @Html.ValidationMessageFor(model => model.ProjectId)
    </div>

Models have been set up using FKs and virtual attributes. When I use the scafolded create view at /ProjectDocument/Create the dropdown is populated as expected. I will be grateful for any assistance.

Was it helpful?

Solution

I like to use a static method in these cases. on your controller

public static List<SelectListItem> GetDropDown(){
    List<SelectListItem> ls = new List<SelectListItem>();
    var data = //call the database;
    foreach(var temp in data){
        ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
    }
    return ls
}

and then on your view

@Html.DropDownList("ProjectId", PathToController.GetDropDown())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top