Reputation: 57
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="&Segment=1000",Text="1,000+"},
new SelectListItem{ Value="&Segment=750-999",Text="750-999"},
new SelectListItem{ Value="&Segment=500-749",Text="500-749"},
new SelectListItem{ Value="&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!
Upvotes: 0
Views: 197
Reputation: 218722
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 :)
Upvotes: 1