我有这个下拉列表,它从db获取数据,但在视图中没有正确显示数据
代码如下:
查看:
@Html.DropDownListFor(m=> Model.SystemRAteModel.Role, new SelectList(Model.SystemRAteModel.GetRole.Items),"Value","Text")
型号:
public class SystemRolesModel
{
public static RoleProvider Provider { get; internal set; }
public int ID { get; set; }
public String Role { get; set; }
public Boolean Status { get; set; }
public SelectList GetRole { get; set; }
}
控制器
public ActionResult Index()
{
IApplicationLogic app = new ApplicationLogic(session);
RateManagementModel RTM = new RateManagementModel();
var value = app.GetVatValue();
var freight = app.GetFreightValue();
// var systemrolemodel = new SystemRolesModel();
//var currency = new List<SelectList>();
// currency= app.GetListOfRoles();
//IList<string> ERModel = new List<string>();
//foreach (var _currency in currency)
//{
// var curent = _currency.ToString();
// ERModel.Add(curent);
//}
var sysmodel = new SystemRolesModel();
sysmodel.GetRole = getRoleSelectList();
RTM.SystemRAteModel = sysmodel;
ViewData["ViewVatValue"] = value;
//ViewData["ViewCurrency"] = new SelectList(currency);
//ViewBag.LocationList = freight;
ViewData["ViewFreightValue"] = freight;
return View("Index",RTM);
}
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles();
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
IEnumerable<SystemRoles> sortedRoles = roles.OrderBy(d => d.Id);
IList<SystemRoles> _sortedRoles = sortedRoles.ToList();
return new SelectList(_sortedRoles, "Id", "Role");
}
我已尝试过网上的所有内容,但无法抓住它。请任何帮助。OutPut of my System At the moment
答案 0 :(得分:0)
您不需要在View中再次创建新的SelectList
,因为您已经在控制器端创建并通过Model传递它,您应该能够在View中直接使用它:
@Html.DropDownListFor(m=> Model.SystemRAteModel.Role,Model.SystemRAteModel.GetRole)
这应该使用值填充下拉列表,但它现在将显示所有项目的相同值,因为您的代码在此处为所有属性设置硬编码的相同值:
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
您需要将其更改为具有适当的值。
另一种简单的方法是以这种方式使用SelectList
的构造函数:
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles().OrderBy(x=> x.RoleID);
return new SelectList(roles.ToList(), "RoleID", "Role");
}
您只需要将RoldID
和Role
属性名称替换为DTO中的专有名称。
希望它有所帮助。
答案 1 :(得分:0)
见这个例子:
@Html.DropDownList("Name", Model.Select(modelItem => new SelectListItem
{
Text = modelItem.Name,
Value = modelItem.Id.ToString(),
Selected = modelItem.Id == "12314124"
}))