Nat*_*lor 11 asp.net-mvc templates preview
随着MVC 2添加了HtmlHelper EditorFor(),无法为给定的Model对象创建强类型的Display和Editor模板,在摆弄它之后,我有点难过如何将其他Model数据传递给编辑器而不会丢失编辑器控件的强类型.
经典示例:产品有类别.ProductEditor有一个包含所有类别名称的DropDownList.ProductEditor是对产品的强类型,我们需要传递类别的选择列表以及产品.
使用标准视图,我们将模型数据包装在一个新类型中并传递它.如果我们传入一个包含多个对象的混合模型,那么使用EditorTemplate会丢失一些标准功能(我注意到的第一件事就是所有的LabelFor/TextBoxFor方法都生成像"Model.Object"这样的实体名称,而不仅仅是"对象" ").
我做错了还是Html.EditorFor()有一个额外的ViewDataDictionary/Model参数?
Haa*_*ked 13
您可以创建具有两个属性的自定义ViewModel,也可以使用ViewData传递该信息.
小智 5
我还在学习,但我遇到了类似的问题,我制定了一个解决方案.我的类别是一个枚举,我使用模板控件检查枚举以确定Select标签的内容.
它在视图中用作:
<%= Html.DropDownList
(
"CategoryCode",
MvcApplication1.Utility.EditorTemplates.SelectListForEnum(typeof(WebSite.ViewData.Episode.Procedure.Category), selectedItem)
) %>
Run Code Online (Sandbox Code Playgroud)
"类别"的枚举使用"描述"属性进行修饰,以用作"选择项目"中的文本值:
public enum Category
{
[Description("Operative")]
Operative=1,
[Description("Non Operative")]
NonOperative=2,
[Description("Therapeutic")]
Therapeutic=3
}
private Category _CategoryCode;
public Category CategoryCode
{
get { return _CategoryCode; }
set { _CategoryCode = value; }
}
Run Code Online (Sandbox Code Playgroud)
SelectListForEnum使用枚举定义和当前所选项的索引构造选择项列表,如下所示:
public static SelectListItem[] SelectListForEnum(System.Type typeOfEnum, int selectedItem)
{
var enumValues = typeOfEnum.GetEnumValues();
var enumNames = typeOfEnum.GetEnumNames();
var count = enumNames.Length;
var enumDescriptions = new string[count];
int i = 0;
foreach (var item in enumValues)
{
var name = enumNames[i].Trim();
var fieldInfo = item.GetType().GetField(name);
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
enumDescriptions[i] = (attributes.Length > 0) ? attributes[0].Description : name;
i++;
}
var list = new SelectListItem[count];
for (int index = 0; index < list.Length; index++)
{
list[index] = new SelectListItem { Value = enumNames[index], Text = enumDescriptions[index], Selected = (index == (selectedItem - 1)) };
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
最终的结果是一个很好的DDL.
希望这可以帮助.任何关于更好的方法的评论将不胜感激.