What is this line of code ViewBag.RoleId = new SelectList(RoleManager.Roles, “Id”, “Name”)

佐手、 提交于 2019-12-02 09:28:14

This line

ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name") 

is creating a SelectList used by the @Html.DropDownList() or @Html.DropDownListFor() helpers to render the options in a <select> tag. The options will have a valueattribute defined by the Id property of Role and a display text defined by the Name property.

The view is using

@Html.DropDownList("RoleId","No Roles")

which binds to ViewData property RoleId (the ViewBag property) and the second argument renders an option label (the first option will have no value, but display the text "No Roles"

This is not a good usage, and it is recommended you use strongly typed helpers to bind to your model properties.

ViewBag.RoleList = new SelectList(RoleManager.Roles, "Id", "Name")

@Html.DropDownListFor(m => m.RoleID, (SelectList)ViewBag.RoleList,"No Roles")

where RoleID is a property in the model that will be bound to the selected options value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!