Binding a Generic List to a Dropdownlistfor in MVC3

独自空忆成欢 提交于 2019-12-08 01:56:31

问题


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)

回答1:


Try to avoid dynamic stuff like ViewBag and ViewData. 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

public class Product
{
  public string Name { set;get;}
  public IEnumerable<SelectListItem> Categories{ get; set; }
  public string SelectedCategoryId { get; set; }
  //Other Properties as needed

}

now in your GET action method, you create an object of this view model and initialize the values and send to the view.

public ActionResult Create()
{
  var vm=new Product();
  vm.Categories=userRepository.Getddl().
               Select(c => new SelectListItem
                                 {
                                    Value = c.DropDownID.ToString(),
                                    Text = c.DropDownText
                                 });                    
  return View(vm);
}

Now make your view strongly typed to our Product class and use the Html.DropDownListFor helper method.

@model PersonsProduct 
@using (Html.BeginForm())
{ 
  @Html.DropDownListFor(x => x.SelectedCategoryId, 
                       new SelectList(Model.Categories,"Value","Text"), "Select")
  <input type="submit" value="save" />
}

Now in your HttpPost , you can get the form values like this

[HttpPost]
public ActionResult Create(Product model)
{
  if(ModelState.IsValid)
  {
     //check model.SelectedCategoryId
     //save and redirect
  }
  //to do :reload the dropdown again.
  return view(model);
}



回答2:


Should just be:

Controller:

IEnumerable<SelectListItem> liCat = userRepository.Getddl().Select(c => new SelectListItem
{
   Value = c.DropDownID.ToString(),
   Text = c.DropDownText
}

ViewBag.catItems = liCat

View:

@Html.Dropdownlist("catItems", ViewBag.catItems)


来源:https://stackoverflow.com/questions/12877601/binding-a-generic-list-to-a-dropdownlistfor-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!