这几天在做项目时,遇到在添加页面用<select>做的下拉框,在修改页面不知道怎么调用形成下拉框。所以查了百度,找到以上方法,整合了一下,根据自己的情况,试着写了一下,代码中的INFORMATION是model类。
因为楼主用的数据库优先,所以是在Controller中定义的类。
Controller代码为:
public class SelectInfo
{
public static List<SelectListItem> GetSelectList()
{
List<SelectListItem> selectList = new List<SelectListItem>(){
new SelectListItem(){Value="Enable",Text="启用"},
new SelectListItem(){Value="Disable",Text="禁用"}
};
return selectList;
}
}
Controller中的添加代码:
public ActionResult Add()
{
ViewBag.Options = SelectInfo.GetSelectList();
return View();
}
[HttpPost]
public ActionResult Add(FormCollection from)
{
string time = System.DateTime.Now.ToString();
INFORMATION addToInfo = new INFORMATION();
addTo.TITLE = from["information_title"];
addTo.CONTENT = from["information_content"];
addTo.USER_NAME = Session["username"].ToString();
addTo.UP = DateTime.Parse(time);
addTo.TYPE = from["type"];
db.LRS_INFO_MGT.Add(addToInfo);
db.SaveChanges();
return Content("<script>alert('添加成功。');window.location.href='/Information/InfoIndex'</script>");
}
}
View中的添加页面:
<td width="10%"><p align="right">是否启用:</td>
<td colspan="3"><p align="left">
@Html.DropDownListFor(model=>model.TYPE,ViewBag.Options as IEnumerable<SelectListItem>)
@Html.ValidationMessageFor(model=>model.TYPE)
</td>
</tr>
Controller中的修改代码:
</pre><p><pre name="code" class="csharp">public ActionResult Edit(decimal id)
{
INFORMATION info = (from a in db.INFORMATION
where a.INFORMATION_ID == id
select a).FirstOrDefault();
if (info == null)
{
return HttpNotFound();
}
ViewBag.Options = SelectInfo.GetSelectList();
return View(info);
}
[HttpPost]
public ActionResult Edit(INGORMATION info)
{
if (!ModelState.IsValid)
{
return View();
}
else
{
db.Entry(info).State = EntityState.Modified;
db.SaveChanges();
return Content("<script>alert('修改成功。');window.location.href='/Information/InfoIndex'</script>");
}
}
View中的修改页面:
<td width="10%"><p align="right">是否启用:</td>
<td colspan="3"><p align="left">
@Html.DropDownListFor(model=>model.TYPE,ViewBag.Options as IEnumerable<SelectListItem>)
@Html.ValidationMessageFor(model => model.TYPE)
</td>
</tr>
做完以上之后,就能实现:下拉框(启用、禁用),当你在添加页面添加时,若选择了”禁用“;修改页面就能显示“禁用”。
提示:若在添加页面,不能用强类型。那么就用<select>标签,例如:
<div class="font4 float-l name"><span style="font-family: Arial, Helvetica, sans-serif;">是否启用</span><span style="font-family: Arial, Helvetica, sans-serif;">:</span>
<select name="type" >
<option value="Enable">启用</option>
<option value="Disable">禁用</option>
</select> </div>
这样只要把value的值对应好,修改也不会出错。