專案:mvc4
動機:登錄畫面上新增學歷的DropDownList
1.建立學歷的models
public class EduDegree
{
public string degree_no { get; set; }
public string name { get; set; }
}
2. 利用DataContext的ExecuteQuery將學歷放到List中
public class EduDegreeContext : DataContext
{
public EduDegreeContext() : base(ConfigurationManager.ConnectionStrings["MyConn"].ToString()) { }
public static List EduDegrees = null;
public IEnumerable GetAll()
{
if (EduDegrees == null)
{
var results = ExecuteQuery ("SELECT ed_degree_no AS degree_no, ed_degree_name AS name FROM comm_edu_degree");
EduDegrees = results.ToList();
}
return EduDegrees;
}
}
3.Controller中利用ViewBag來傳遞資料集合到view
EduDegreeContext edc = new EduDegreeContext();
ViewBag.Degree = edc.GetAll().ToList();
4.view端程式
@{
List list = ViewBag.Degree;
var items = new SelectList(list, "degree_no", "name");
}
//透過DropDownListFor的顯示
@Html.DropDownListFor(m => m.Degree, @items)
留言列表