<%@ 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'的定义,并且没有扩展方法'CorpDictionary'接受类型'object'的第一个参数可以找到
以及我的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; }
}
答案 0 :(得分:3)
首先,您没有使用链接,您只是使用lambda表达式来指定模型上的属性。其次,您的视图需要从ViewPage继承,在这种情况下,是一个特定于您的模型的强类型视图页面。第三,我建议你有一个属性用于CorporationId(从select的值回发)和一个IEnumerable<SelectListItem>
来提供下拉列表的值,而不是使用魔术字符串来构造一个SelectList。这可以使用LINQ或扩展方法来进行选择。
通常情况下,我不会将视图模型放在容器之外 - 它应该与数据库无关。从DB中填充控制器中的视图模型。
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<EveNotebook.ViewModels.CorporationJoinViewModel>"
%>
<%: Html.DropDownListFor(c => c.CorporationId, Model.CorpDictionary )%>
型号代码
public class CorporationJoinViewModel
{
public int CorporationId { get; set; }
public IEnumerable<SelectListItem> CorpDictionary { get; set; }
}
控制器代码
...
var model = new CorporationJoinViewModel
{
CorpDictionary = _eveNotebook.Corporations.Select( c => new SelectListItem
{
Text = c.name,
value = c.id.ToString()
}
};