如何在ASP MVC 5中创建IEnumerable
下拉列表?
我使用此功能但它显示错误:
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>
具有键&#39; Reshte&#39;的ViewData项。属于&#39; System.Int32&#39;但必须属于&#39; IEnumerable&#39;。
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 :(得分:0)
您必须定义新的viewModel,如下所示
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" })