gpt4 book ai didi

c# - List 如何在 View 中安全地转换为 SelectList

转载 作者:可可西里 更新时间:2023-11-01 08:25:26 25 4
gpt4 key购买 nike

我正在关注一个问题,其中 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 中查找键>.

我基于 http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/5cb74eb3b2f3#src/System.Web.Mvc/Html/SelectExtensions.cs

他们甚至添加了评论:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com