【发布时间】:2011-07-19 08:41:21
【问题描述】:
我正在使用带有 Razor 视图的 MVC3,并希望为我的几个类构建可重用的 DropDownLists,但经过大量搜索后,我没有找到一个完全符合我需要的示例......
对于这个例子,我有两个这样的类:-
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
}
public class Group
{
public int ID { get; set; }
public string Name { get; set; }
}
我有一个用于 Person 的工作控制器/视图。该视图有一个 DropDownListFor 控件:
@model Person
...
@Html.DropDownListFor(o => o.Group.ID, (ViewData["groups"] as SelectList))
视图直接使用 Person 类,而不是中间模型,因为在这个阶段我还没有找到一个令人信服的理由将一个与另一个抽象出来。
以上工作正常...在控制器中,我从视图返回的 Person 中的 Group.ID 中获取值,查找它,并将 Person.Group 设置为结果。有效,但并不理想。
我在这里找到了一个活页夹:MVC DropDownList values posted to model aren't bound,它可以帮我解决这个问题,但我还没有完成这个工作......因为它只有在我可以重复使用时才真正有用。
我想做的是在模板中有这样的东西:-
@model Group
@Html.DropDownListFor(o => o.Group.ID, (ViewData["groups"] as SelectList))
并在这样的视图中使用它:-
@Html.EditorFor(o => o.Group)
但是上面似乎不起作用...上面的 EditorFor 行插入了整个类的编辑器(例如 Group.Description 的文本框)...而不是插入包含我的组的 DropDownList
我在 Views/Shared/EditorTemplates 下名为 Group.cshtml 的文件中有上述模板
如果这可行,那么只要一个类具有 Group 类型的属性,就会默认使用此 DropDownList 编辑器(或至少在某些属性指定的情况下)
提前感谢您提供的任何建议...
【问题讨论】:
标签: asp.net-mvc-3 templates drop-down-menu razor editor