0

I have the following code in my model:

   public class ProjectViewModel
   {
     [Display(Name = "Project Status")]
     public int SelectedStatusId { get; set; }
     public SelectList StatusList { get; set; }
   }

Following is the class (which is inside the Repository Folder) that retrieves set of status from database:

public IEnumerable<SelectListItem> LoadStatus()
    {
        using (ProjectEntities proj = new ProjectEntities())
        {
            var statList = proj.ProjectStatus.Select(x => new SelectListItem
            {
                Value = x.ProjStatusID.ToString(),
                Text = x.ProjStatusCode
            });
            return new SelectList(statList, "Value", "Text");
        }

    }

Following is my code on Controller:

public class ProjectMasterController : Controller
{
   public ActionResult LoadProjectStatus()
    {
        ProjectDataManager pm = new ProjectDataManager();
        var model = new ProjectViewModel();

        model.StatusList = new SelectList(pm.LoadStatus(), "ProjStatusID",   "ProjStatusCode");

        return View(model);
    }
}

And, finally the View:

@Html.LabelFor(model => model.SelectedStatusId)
@Html.DropDownListFor(model => model.SelectedStatusId, Model.StatusList,"Select Status")

I have referred the answer1 and answer2 on StackOverflow. But I am getting an error,

The ViewData item that has the key 'SelectedStatusId' is of type 'System.Int32' but must be of type 'IEnumerable'.

I am not sure where i am going wrong

Community
  • 1
  • 1
  • In addition to the dupe, change your property to `public IEnumerable StatusList { get; set; }` - You create one `IEnumerable` in the `LoadStatus` method. Then you create another identical one from it using `return new SelectList(statList, "Value", "Text");`. Then you create a 3rd identical one in the `LoadProjectStatus()` by using `model.StatusList = new SelectList(..)` again –  Jul 17 '16 at 22:18

2 Answers2

0

Take a look at this line.

 model.StatusList = new SelectList(pm.LoadStatus(), "ProjStatusID",   "ProjStatusCode");

But your pm.LoadStatus returns a a list of SelectListItem. Each item in the list will have Value property and Text property, There will not be a ProjeStatusID and ProjStatusCode property. That line is going to crash!

This should solve that problem.

 model.StatusList = new SelectList(pm.LoadStatus(), "Value",   "Text");

or even

vm.StatusList = pm.LoadStatus() as SelectList;
Shyju
  • 214,206
  • 104
  • 411
  • 497
-1

Change your code in controller to below model.StatusList = pm.LoadStatus()

rachit
  • 83
  • 1
  • 9