来自不同实体的 MVC 下拉列表
我有一个视图,即继承自 System.Web.Mvc.ViewPage
。
类型 P 具有类型 C
的属性,即 P
可以是:
class P
{
public string Name { get; set; }
public C OtherData { get; set; }
}
相关视图用于创建新的 P
,因此我想创建一个包含所有可用 C
的下拉列表。
所以下拉列表可能是:
- C1
- C2
- C3
- C4
我尝试为控制器中的 C
创建 List
对象,然后将它们传递给视图使用 ViewData
但这不起作用,因为当我尝试提交时出现异常:
System.InvalidOperationException: There is no ViewData item of type 'IEnumerable
我的问题是,如何创建一个 C 对象列表以显示在继承自类型 P 的视图中。对象列表是从数据库中提取的,因此我不能简单地将选项硬编码到视图中。
我是否需要创建另一个将这两种类型结合在一起的模型类型?
I have a view, that is of Inherits from System.Web.Mvc.ViewPage<P>
.
Type P has a property of Type C
, ie, P
could be:
class P
{
public string Name { get; set; }
public C OtherData { get; set; }
}
The View in question is for creating a new P
, and as such I want to create a DropDown list of all the available C
's.
So the dropdown could be:
- C1
- C2
- C3
- C4
I've tried creating the List<SelectListItem>
object for the C
's in my controller and then pass them to the view using ViewData
but this does not work, as when I try to submit I get the exception:
System.InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key C.
So my question is, how do I create a list of C
objects to display in my View that inherits from type P
. The list of objects is pulled from a database and as such I cannot just simply hardcode the options into the view.
Do I need to create another Model type that marries the 2 types together?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我执行此操作的方式如下:
ViewModel:
我的 View 具有以下内容:
我使用 Brad Wilson 关于 ASP.NET MVC 2 模板的精彩博客文章系列
然后我在 Views/Shared/EditorTemplates 文件夹中为该下拉列表添加一个下拉模板,并将其命名为 CClassDropDown:
然后我为 P 对象添加一个部分元数据类:
到该类属性的元数据中,以便它知道使用我指定的模板。
The way I do this is as follows:
ViewModel:
My View has the following:
I use the default Object.ascx outlined in Brad Wilson's excellent series of blog posts on ASP.NET MVC 2 Templates
Then I add a dropdown template for that dropdown in the Views/Shared/EditorTemplates folder and call it something like CClassDropDown:
And then I add a partial metadata class for the P object:
to the metadata for that class property so it knows to use the template I specified.
我只用 Linq2Sql 做过这个,所以 YMMW。
在 Linq2Sql 中,实体同时具有外部实体和外部实体键。
因此,它将同时具有 C 和 C_id。
在这种情况下,它只是一个这样做的情况
,并且在页面中
这样
做将正确设置OtherData_id,这反过来将导致OtherData在访问时被解析。
I've only done this with Linq2Sql so YMMW.
In Linq2Sql the entity has both an foreign entity, and a foreign entity key.
So, it would have both C and C_id.
In that case its just a case of doing
and in the page doing
In this way
will correctly set the OtherData_id, which in turn will cause OtherData to be resolved when accessed.