大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

一、非强类型:

Controller:

ViewData[“AreId”] = from a in rp.GetArea()

select new SelectListItem {

Text=a.AreaName,

Value=a.AreaId.ToString()

};

View:

@Html.DropDownList(“AreId”)

还能够给其加上一个默认选项:@Html.DropDownList(“AreId”, “请选择”);

二、强类型:

DropDownListFor经常使用的是两个參数的重载,第一參数是生成的select的名称,第二个參数是数据,用于将绑定数据源至DropDownListFor

Modle:

public class SettingsViewModel

{

Repository rp =new Repository();

public string ListName { get; set; }

public IEnumerable GetSelectList()

{

var selectList = rp.GetArea().Select(a => new SelectListItem {

Text=a.AreaName,

Value=a.AreaId.ToString()

});

return selectList;

}

}

Controller:

public ActionResult Index()

{

return View(new SettingsViewModel());

}

View:

@model Mvc3Applicationtest2.Models.SettingsViewModel

@Html.DropDownListFor(m=>m.ListName,Model.GetSelectList(),”请选择”)

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/118648.html原文链接:https://javaforall.cn