作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在关注一个问题,其中 OP 有类似这样的东西
[HttpGet]
public ActionResult Index() {
var options = new List<SelectListItem>();
options.Add(new SelectListItem { Text = "Text1", Value = "1" });
options.Add(new SelectListItem { Text = "Text2", Value = "2" });
options.Add(new SelectListItem { Text = "Text3", Value = "3" });
ViewBag.Status = options;
return View();
}
然后在 View 中可以做这样的事情
@Html.DropDownList("Status", ViewBag.Status as SelectList)
我的预期是转换的结果是 null
我也这么说了。我被纠正说它应该可以工作,并且它是通过 .net fiddle 演示的。令我惊讶的是,下拉列表中填满了这些项目。
我的问题:在 View 中完成后,List<SelectListItem>
是怎么回事?安全地转换为 SelectList
最佳答案
这是一个很好的问题。我进一步调查了此事,确实,如果 selectList
参数为 null,则 name
参数用于在 ViewData
中查找键>.
他们甚至添加了评论:
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
{
...
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
...
稍后,使用name
:
private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
object o = null;
if (htmlHelper.ViewData != null)
{
o = htmlHelper.ViewData.Eval(name);
}
...
好问题@Nkosi。我不知道这是可能的。
关于c# - List<SelectListItem> 如何在 View 中安全地转换为 SelectList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39979467/
我是一名优秀的程序员,十分优秀!