MVC框架中如何进行List<SelectListItem>绑定
{
//3.1.1 检查id
//3.1.2根据id查询数据
Models.Student stu = (from s in db.Students where s.Id == id select s).FirstOrDefault();
//方法一、查询班级数据,并 做成 下拉框 选项集合
//List<Models.Class> listClass = (from c in db.Classes where c.CIsDel == false select c).ToList();
//ViewBag.classList = listClass;
//方法二 查询班级数据,并转成 下拉框选项 集合
List<SelectListItem> listClass = db.Classes.Where(c=>c.CIsDel==false).ToList()//先查询数据 并 转成 实体List集合
.Select( c=> new SelectListItem() { Text = c.CName, Value = c.CID.ToString(), Selected = (stu.CId == c.CID) }).ToList();//将实体集合 转成 SelectListItem集合
//将 下拉框选项 集合 设置给 ViewBag ,用以传递 到 视图
ViewBag.classList = listClass;
//SelectList
//3.1.加载视图,并孝嫌传递 要修改的数据
return View(stu);
}
2
<table>
<tr>
<td>姓名:</td>
<td><侍穗input type="text" name="Name" value="@Model.Name" /></td>
</tr>
<tr>
<td>班级:</td>
<td>
@* 这是方法一*@
@*<select name="CID">
@foreach (Class s in @ViewBag.classList as List<Class>老慎卜)
{
if(s.CID == Model.CId){
<option selected value="@s.CID">@s.CName</option>
}else{
<option value="@s.CID">@s.CName</option>
}
}
</select>*@
@* 这是方法二*@
@Html.DropDownList("CId", ViewBag.classList as IEnumerable<SelectListItem>)
</td>
</tr>
</table>
3
@* @Html.DropDownList("BelongCollege", ViewBag.BelongCollege as IEnumerable<SelectListItem>)*@
@Html.DropDownListFor(model=>model.BelongCollege, ViewBag.BelongCollegeEnum as IEnumerable<SelectListItem>)
@* <select name="BelongCollege" id="BelongCollege" class="valid">
@foreach (var s in (@ViewBag.BelongCollege as IEnumerable<SelectListItem>))
{
if (int.Parse(s.Value) == Model.BelongCollege)
{
<option selected value="@s.Value">@s.Text</option>
}
else
{
<option value="@s.Value">@s.Text</option>
}
}
</select>*@
public ActionResult Modify(int id)
{
1. 检查id
2.根据id查询数据
Models.Student stu = (from s in db.Students where s.Id == id select s).FirstOrDefault();
方法一:查询班级数据,并 做成 下拉框 选项集合
List<Models.Class> listClass = (from c in db.Classes where c.CIsDel == false select c).ToList();
ViewBag.classList = listClass;
方法二 :查询班级数据,并转成 下拉框选项 集合
List<SelectListItem> listClass = db.Classes.Where(c=>c.CIsDel==false).ToList()//先查询数据 并 转成 实体List集合
.Select( c=> new SelectListItem() { Text = c.CName, Value = c.CID.ToString(), Selected = (stu.CId == c.CID) }).ToList();//将实体集合 转成 SelectListItem集合
将 下拉框选项 集合 设置给 ViewBag ,用以传递 到 视碰物图
ViewBag.classList = listClass;
SelectList
3.加载视图,老老并传递 要修改的数据
return View(stu);}
2
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="Name" value="@Model.Name" /></td>
</tr>
<tr>
<td>班级侍吵升:</td>
<td>