我是 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”的值填充 DropDownListFor
,但我可以从中引用 Controller 代码中的 id。我的想法是,如果用户选择“One”,我会得到一个整数值 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/