Kianoush Kianoush - 22 days ago 4
ASP.NET (C#) Question

Create IEnumerable DropDownList

How can I create an

IEnumerable
dropdown list in ASP MVC 5 ?

I'm using this but it shows me error :

public ActionResult EditStudent()
{
ViewBag.Reshte = new SelectList(_db.Tbl_Reshte, "ReshteID", "ReshteName");
ViewBag.Paye = new SelectList(_db.Tbl_Paye, "PayeID", "PayeName");
return View();
}


View

<div class="form-group">
@Html.LabelFor(x => x.Reshte)
@Html.DropDownListFor(x => x.Reshte, (SelectList) ViewBag.Reshte, "-- رشته دانش آموز ---", htmlAttributes: new {@class = "form-control"})
</div>
<div class="form-group">
@Html.LabelFor(x => x.Paye)
@Html.DropDownListFor(x => x.Paye, (SelectList) ViewBag.Paye, "-- پایه تحصیلی دانش آموز --", htmlAttributes: new {@class = "form-control"})
</div>



The ViewData item that has the key 'Reshte' is of type 'System.Int32' but must be of type 'IEnumerable'.


public partial class Tbl_Reshte
{
public Tbl_Reshte()
{
Tbl_Pye_Reshte = new HashSet<Tbl_Pye_Reshte>();
}

[Key]
public int ReshteID { get; set; }

[StringLength(100)]
public string ReshteName { get; set; }

public virtual ICollection<Tbl_Pye_Reshte> Tbl_Pye_Reshte { get; set; }
}


.

public partial class Tbl_Paye
{
public Tbl_Paye()
{
Tbl_Pye_Reshte = new HashSet<Tbl_Pye_Reshte>();
}

[Key]
public int PayeID { get; set; }

[StringLength(100)]
public string PayeName { get; set; }

public virtual ICollection<Tbl_Pye_Reshte> Tbl_Pye_Reshte { get; set; }
}

Answer

you have to define new viewModel like below

 public class SampleViewModel
 {
    [Display(Name = "رشته")]
    [Required(ErrorMessage = "لطفا یکی از رشته ها را انتخاب نمایید")]
    public int ReshteId { get; set; }
    public List<SelectListItem> ReshteSelectListItems { get; set; }

    [Display(Name = "پایه تحصیلی")]
    [Required(ErrorMessage = "لطفا یکی از پایه ها را انتخاب نمایید")]
    public int PayeId { get; set; }
    public List<SelectListItem> PayeSelectListItems { get; set; }

    //other field....
 }

and your controller

public ActionResult Add()
    {
        var model = new SampleViewModel
        {
            PayeSelectListItems = _db.paye.Select(p=>new SelectListItem {Text =p.PayeName ,Value = PayeID.tostring() }).toList(),
            //ReshteSelectListItems = ...

        };
        return View(model);
    }

finally your View

@Html.DropDownListFor(p => p.ReshteId, Model.ReshteSelectListItems , new { @class = "form-control" })
Comments