I have a generic list method that returns a CategoryID and CategoryName. I have spent enough time researching and cant seem to put it together. I very new at MVC.
Here is my DropdownList Method in a repository. I get back the data... So far so good.
public List<DropdownList> GetDDl()
{
return catDDL;
}
Here is my CONTROLLER CODE(attempt at it)
IEnumerable<SelectListItem> liCat =
userRepository.Getddl().Select(c => new SelectListItem
{
Value = c.DropDownID.ToString(),
Text = c.DropDownText
}
ViewBag.catItems = new SelecList(liCat,"Value","Text");
Here is my VIEW
@Html.Dropdownlist("catItems","Select Category)
Should just be:
Controller:
View:
Try to avoid dynamic stuff like
ViewBag
andViewData
. Use strongly typed views.ViewModel is just a POCO class which we will use to transfer data between your view and the action method. It will be specific to the view.
ex : if you want to create a view which creates a product. So create a viewmodel like this
now in your
GET
action method, you create an object of this view model and initialize the values and send to the view.Now make your view strongly typed to our
Product
class and use theHtml.DropDownListFor
helper method.Now in your HttpPost , you can get the form values like this
I created a generic function for bind dropdownlist e.g