2016-11-12 19 views
-2

如何在ASP MVC 5中創建IEnumerable下拉列表?創建IEnumerable DropDownList

我用這一點,但它爲我的錯誤:

public ActionResult EditStudent() 
    { 
     ViewBag.Reshte = new SelectList(_db.Tbl_Reshte, "ReshteID", "ReshteName"); 
     ViewBag.Paye = new SelectList(_db.Tbl_Paye, "PayeID", "PayeName"); 
     return 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> 

具有關鍵 'Reshte' 的類型爲 'System.Int32' 的ViewData的項目但必須是「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; } 
} 
+0

正確的標題和第一句:IEnumerable,而不是IEnumerabel –

+0

好的。謝謝 。你有指導嗎? – Kianoush

+0

你可以添加你使用的模型類嗎? – CodeNotFound

回答

0

你必須定義像下面

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.... 
} 

和你控制器

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); 
    } 

最後你的查看新視圖模型

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