How to convert a table to an IEnumerable to show it in a Dropdownlistfor

0

Good morning, I'm learning c # ASP .NET MVC, How can you convert a table to IEnumerable to use it in Dropdownlistfor ?: I have the following model:

public class Saleform
    {
        public int ID { get; set; }
        public int SaleaccountID { get; set; }
        public int LeadsourceID { get; set; }
        public int SalestageID { get; set; }
        public int VerifyCodeViewModelCode { get; set; }
        public string Name { get; set; }
        public float Likely { get; set; }
        public DateTime Dateup { get; set; }
        public virtual Salestage Salestage { get; set; }
        public virtual Leadsource Leadsource { get; set; }
        public virtual Saleaccount Saleaccount { get; set; }
    }

In another file I have the model referenced:

public class Leadsource
{
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Saleform> Forms { get; set; }
}

In the controller:

public ActionResult Create()
{
          IEnumerable<Leadsource> Ileadsourcelist = (from x in db.Leadsources 
          select x).ToList<Leadsource>();
          ViewData["Leadsourcenamelist"] = Ileadsourcelist;
          return View();
}

In the view:

   @Html.DropDownListFor(model => model.LeadsourceID, 
   (IEnumerable<SelectListItem>)ViewData["Leadsourcenamelist"])

The error that marks is that it can not convert information of type List to type IEnumerable .

Thank you.

    
asked by Egb 10.10.2017 в 00:12
source

3 answers

1

You can create a SelectList from a List in the table

List<Tabla> lista = (from r in context.NombreTabla orderby r.campoordenar select r).ToList();

SelectList select = new SelectList(lista, "nombreCampoValor", "nombreCampoDescripcion");

@Html.DropDownListFor(model => model.atributoModel, select, otros atributos);

Normally the SelectList implemented it in a method within the Model

public SelectList getSelectList(){
  return new SelectList(lista, "nombreCampoValor", "nombreCampoDescripcion");
}

and in the view

@Html.DropDownListFor(model => model.atributoModel, Model.getSelectList(), otros atributos);
    
answered by 10.10.2017 в 06:09
0

Regards

In your Controller try the following:

public ActionResult Create()
{
   IEnumerable<Leadsource> Ileadsourcelist = db.Leadsources.AsEnumerable(); // <<<-- Este es el cambio
   ViewData["Leadsourcenamelist"] = Ileadsourcelist;
   return View();
}

Personally I prefer to use List ; such that I suggest you use:

List<Leadsource> Ileadsourcelist = db.Leadsources.AsEnumerable().ToList(); 

I hope you find it useful.

    
answered by 10.10.2017 в 00:30
0

Thanks. I am already resolved:  IEnumerable Ileadsourcelist = new SelectList (db.Leadsources.ToList (), "ID", "Name");  ViewData ["Leadsourcenamelist"] = Ileadsourcelist;

    
answered by 11.10.2017 в 21:16