gpt4 book ai didi

c# - 用值填充下拉列表

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

我是 MVC 的初学者,正在尝试用值填充 DropDownListFor 标记。

这是我现在发现的,对我构建代码有所帮助:

http://forums.asp.net/t/1705047.aspx/1

所以在我的 Controller 中现在有 2 个类,主类 (ObjController : Controller) 和另一个我按照上面的例子编写的类。

另一个类是这样的:

public class ItemCostViewModel
{
public int Id { get; set; }

[Required]
[Display(Name = "Item Cost :")]
public string ItemCostCode { get; set; }

public IEnumerable<ItemCostViewModel> GetItemCosts()
{
return new List<ItemCostViewModel>
{
new ItemCostViewModel() {Id = 1, ItemCostCode = "One"},
new ItemCostViewModel() {Id = 2, ItemCostCode = "Two"},
new ItemCostViewModel() {Id = 3, ItemCostCode = "Three"},
new ItemCostViewModel() {Id = 4, ItemCostCode = "Four"},
new ItemCostViewModel() {Id = 5, ItemCostCode = "Five"},
new ItemCostViewModel() {Id = 6, ItemCostCode = "Six"}
};
}
}

所以这里的目标是用显示“One”但我可以从中引用 Controller 代码中的 id 的值填充 DropDownListFor。我的想法是,如果用户选择“一”,我会得到一个整数值 1,我可以相应地处理它。

我已经在 .cshtlm View 中尝试了这行代码:

@Html.DropDownListFor(m => m.ItemCostCode , new SelectList(new Project1.Controllers.ItemCostViewModel().GetItemCosts(), "Id", "ItemCostCode"))

但遗憾的是,它会引发崩溃,因为 ItemCostCode 不在 Controller 中:

Compiler Error Message: CS1061:'System.Collections.Generic.IEnumerable<Project1.Models.ObjectInfo>' does not containt a definition for "ItemCostCode" (...)

我很困惑,我不确定我现在在做什么,以及如何做。谁能帮我解释一下出了什么问题,和/或如何纠正它?

非常感谢!

最佳答案

以下是我建议您解决问题的方法:

1) 将该 GetItemCosts() 方法的签名更改为返回一个列表。无论如何,您都在这样做,并且在后续步骤中会更容易。

2) 在您的 Controller 中设置以下内容(使用您调用 GetItemCosts() 所做的一切):

var itemCodeList = new List<DropDownItem>();

GetItemCosts().ForEach(ic => itemCodeList.Add(new DropDownItem { Value = ic.ID, Text = ic.ItemCostCode} );

ViewData["ItemCodes"] = itemCodeList;

3) 您 View 中的行现在应该如下所示:

@Html.DropDownListFor(m => m.ItemCostCode , ((IEnumerable<DropDownItem)(ViewData["ItemCodes"])))

关于c# - 用值填充下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14861356/

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