gpt4 book ai didi

c# - 将 Razor 选择绑定(bind)到来自 VewData 的字典

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:51 25 4
gpt4 key购买 nike

我正在使用 .NET Core MVC(dotnet 版本 1.0.4)编写网络应用。

我想传递一个 Dictionary<string, string>ViewData从 Controller 查看对象并将其绑定(bind)到 <select>元素。

这是我想要得到的结果:

enter image description here

我尝试了两种方法来实现它。

第一种方式

Controller 代码

Dictionary<string, string> animals = new Dictionary<string, string>();
animals.Add("1", "cat");
animals.Add("2", "dog");
animals.Add("3", "bunny");

ViewData["animals"] = new SelectList(animals);

View 代码

<select asp-for="Animal_id" asp-items="(SelectList)@ViewData["animals"]" class="form-control"></select>

这给了我这个结果

enter image description here

第二种方式

Controller 代码

Dictionary<string, string> animals = new Dictionary<string, string>();
animals.Add("1", "cat");
animals.Add("2", "dog");
animals.Add("3", "bunny");

ViewData["animals"] = new SelectList(animals.Select(r => new SelectListItem
{
Text = r.Key,
Value = r.Value
}));

View 代码

一样。

这给了我这个结果:

enter image description here

显然,我对这个概念有些不理解,尽管我觉得我在正确的轨道上。你能帮帮我吗 - 需要做什么才能从我的第一张照片中得到结果( <option> s 和 value s)?

最佳答案

您使用了 SelectList 的重载参数为 IEnumerable 的构造函数.该重载调用 .ToString()您集合中每个项目的方法,并且因为它们是复杂的对象,所以您会得到您所看到的结果。只有当你的收藏是 IEnumerable<string> 时,这个重载才有用。 .

您需要使用接受参数的重载 dataValueFielddataTextField它定义了用于选项值和显示文本的属性。

Dictionary<string, string> animals = new Dictionary<string, string>();
animals.Add("1", "cat");
animals.Add("2", "dog");
animals.Add("3", "bunny");

ViewData["animals"] = new SelectList(animals, "Key", "Value");

另请注意,在您的第二个示例中,您已经生成了一个 IEnumerable<SelectListItem>使用 new SelectList(...)创建一个相同的 IEnumerable<SelectListItem>从第一个开始是毫无意义的额外开销,它可以是

ViewData["animals"] = animals.Select(r => new SelectListItem
{
Text = r.Key,
Value = r.Value
}));

并在 View 中asp-items="(IEnumerable<SelectListItem>)@ViewData["animals"]"

关于c# - 将 Razor 选择绑定(bind)到来自 VewData 的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45683472/

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