gpt4 book ai didi

asp.net - DropDownListFor 并将我的 lambda 与我的 ViewModel 相关联

转载 作者:行者123 更新时间:2023-12-02 10:43:21 24 4
gpt4 key购买 nike

在谷歌搜索了一段时间后,我仍然一片空白。我正在尝试使用 ViewModel 来拉取字典并将其提供给强类型 View 内的下拉列表:

<%@ 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' does not contain a definition for 'CorpDictionary' and no extension method 'CorpDictionary' accepting a first argument of type 'object' could be found

以及我的 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 对象有一种非常神奇的理解,而错误消息让我认为事实并非如此。我的问题是我用来传递数据的方法吗?我在这里缺少什么?

<小时/>

解决方案

(与优秀答案非常相似,但运行了编译器并修复了过程中的一些拼写错误):

Controller

  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))%>

View 模型

public class CorporationJoinViewModel : ViewPage
{
public int CorporationId { get; set; }

public IEnumerable<SelectListItem> Corps { get; set; }
}

最佳答案

首先,您没有使用链接,您只是使用 lambda 表达式来指定模型上的属性。其次,您的 View 需要继承 ViewPage,在本例中,是特定于您的模型的强类型 View 页面。第三,我建议您有一个 CorporationId 属性(从选择的值回发)和 IEnumerable<SelectListItem>为下拉列表提供值,而不是使用魔术字符串来构造 SelectList。这可以使用 LINQ 或扩展方法来进行选择。

通常,我不会让 View 模型成为容器以外的任何东西——它应该与数据库无关。从数据库填充 Controller 中的 View 模型。

<%@ 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; }
}

Controller 代码

...
var model = new CorporationJoinViewModel
{
CorpDictionary = _eveNotebook.Corporations.Select( c => new SelectListItem
{
Text = c.name,
value = c.id.ToString()
}
};

关于asp.net - DropDownListFor 并将我的 lambda 与我的 ViewModel 相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2892113/

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