asp.netasp.net-mvc-4html-helperdropdownlistfor

asp.net mvc 4 dropdown list with model isn't working


I'm converting an asp.net forms site to MVC and am having an issue with a dropdown list.

Model extract:
namespace adminLte.Models
//then further down

[Required(ErrorMessage = "Player Segment Required")]  
[Display(Name = "Player Segment")]  
public string Segment { get; set; }  
public IEnumerable<SelectListItem> PlayerSegmentList { get; set; } 

//model class List

public IEnumerable<SelectListItem> getPlayerSegmentList()  
{  
  List<SelectListItem> myList = new List<SelectListItem>();  
  var data = new[]{  
   new SelectListItem{ Value="&amp;Segment=1000",Text="1,000+"},  
   new SelectListItem{ Value="&amp;Segment=750-999",Text="750-999"},  
   new SelectListItem{ Value="&amp;Segment=500-749",Text="500-749"},  
   new SelectListItem{ Value="&amp;Segment=400-499",Text="400-499"}
  };
  myList = data.ToList();
  return myList;
}  

controller:
//?? not sure about this...

playerExtract objModel = new playerExtract();
objModel.PlayerSegmentList = objModel.getPlayerSegmentList();
ViewBag.pSeg = new SelectList(objModel, "SegmentID", "Segment"); 

*HTML form*  
@Html.LabelFor(model => model.Segment, htmlAttributes: new {  @class = "control-label col-md-2" })  
@Html.DropDownListFor( model => model.Segment, ViewBag.pSeg as SelectList  , new { htmlAttributes = new { @id = "Segment", @class = "form-control" } })  
@Html.ValidationMessageFor(model => model.Segment, "", new { @class = "text-danger" })  

//Results compile error

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Segment'.  

I'm new to MVC and am missing something - Any assistance provided is greatly appreciated!


Solution

  • You should use Model.PlayerSegmentList as your source collection used to build the select options. So pass that as the second parameter of your Html.DropDownListFor method call.

    @Html.DropDownListFor(model => model.Segment, Model.PlayerSegmentList,
                     new { htmlAttributes = new { @id = "Segment", @class = "form-control" } })
    

    Also in your controller code, this line does not make any sense!

    ViewBag.pSeg = new SelectList(objModel, "SegmentID", "Segment"); 
    

    The first parameter of the SelectList has to be a collection, not your class object! That should give you a compile time error!. Just remove that line since you already have the data you needed in your PlayerSegmentList property

    So your cleaned up controller code would be

    public ActionResult Create()
    {
      var vm = new YourVieWModel();
      var objModel = new playerExtract();
      vm.PlayerSegmentList = objModel.getPlayerSegmentList();
      return View(vm); 
    }
    

    That should work assuming you are view is strongly typed tot he same YourViewModel

    I would also recommend using PascalCasing for C# class names/method names :)