【发布时间】:2023-03-15 09:28:01
【问题描述】:
谷歌搜索了一段时间后,我仍然在这里画一个空白。我正在尝试使用 ViewModel 来拉取字典并将其提供给强类型视图中的下拉列表:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="EveNotebook.ViewModels.CorporationJoinViewModel" %>
...
<%: Html.DropDownListFor(c => c.CorpDictionary.Keys, new SelectList(Model.CorpDictionary, "Value", "Key"))%>
我收到了错误:
CS1061:“object”不包含“CorpDictionary”的定义,并且找不到接受“object”类型的第一个参数的扩展方法“CorpDictionary”
以及我的 ViewModel 的相关部分
public class CorporationJoinViewModel
{
DB _eveNotebook = new eveNotebookDB(); // data context
public Dictionary<int, string> CorpDictionary
{
get
{
Dictionary<int, string> corporations = new Dictionary<int, string>();
int x = 0;
foreach (Corporation corp in _db.Corporations)
{
corporations.Add(x, corp.name);
}
return corporations;
}
}
我承认我对 linq 如何从该 lambda 中找到我的 ViewModel 对象有一个非常神奇的理解,而错误消息让我认为它不是。我的问题是我用来传递数据的方法吗?我在这里错过了什么?
解决方案
(与优秀的答案非常相似,但通过编译器并修复了过程中的一些错别字):
控制器
var model = new CorporationJoinViewModel
{
Corps = _eveNotebook.Corporations.Select( c => new SelectListItem
{
Text = c.name,
Value = c.id.ToString()
})
};
return View(model);
查看
Inherits="System.Web.Mvc.ViewPage<IEnumerable<EveNotebookLibrary.Models.Corporation>>" %>
...
<%: Html.DropDownListFor(c => c.Corps, new SelectList(Model.Corps))%>
视图模型
public class CorporationJoinViewModel : ViewPage
{
public int CorporationId { get; set; }
public IEnumerable<SelectListItem> Corps { get; set; }
}
【问题讨论】:
标签: asp.net .net asp.net-mvc data-binding