在MVC中添加类EditorFor [英] Adding class to EditorFor in MVC

查看:171
本文介绍了在MVC中添加类EditorFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想说明枚举在EditorFor。我用编辑模板证明这一点。(DropDownList的)。

我有鉴于麦芽 EditorFor 。我想设置类的一些控制。

  @ Html.EditorFor(M = GT; m.Position,新{@class =smallinput,风格=宽度:150像素重要!})
@ Html.EditorFor(M = GT; m.DocumentType)

在编辑:查看/共享/ DisplayTemplates / Enum.cshtml

  @model枚举
@ {
   VAR值= Enum.GetValues​​(ViewData.ModelMetadata.ModelType).Cast<对象>()
                 。选择(V =>新建SelectListItem
                 {
                     选择= v.Equals(型号)
                     文本= v.GetDisplayName(),
                     值= v.ToString()
                 });
}
@ Html.DropDownList(,价值)

在型号

  [DisplayName的(نوعسند)]
[UIHint(枚举)]
公共DocumentType DocumentType {搞定;组; }


解决方案

您可以通过类名的 EditorTemplate 使用 AdditionalViewData

在主视图

  @ Html.EditorFor(M = GT; m.DocumentType,新{htmlAttributes = {新@class =MyClass的}})

,并在 EditorTemplate

  ....
@ Html.DropDownListFor(M = GT;男,价值观,计算机[htmlAttributes])

然而,包括在 EditorTemplate 是不是好的做法为的SelectList 的逻辑。我建议你​​考虑为生成的SelectList 扩展方法,然后这个 EditorTemplate 不会是必需的。 <一href=\"http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc\">Refer这个例子的。和选择= v.Equals(模型)是没有意义的,因为属性将被忽略(选定的项目将是的值 DocumentType

I want to show Enum in EditorFor. I use Editor Template for show it.(DropDownList).

I have malty EditorFor in view. I want to set class for some controls.

@Html.EditorFor(m => m.Position, new { @class = "smallinput", style = "width:150px !important" })
@Html.EditorFor(m => m.DocumentType)

In Editor: Views/Shared/DisplayTemplates/Enum.cshtml

@model Enum
@{
   var values = Enum.GetValues(ViewData.ModelMetadata.ModelType).Cast<object>()
                 .Select(v => new SelectListItem
                 {
                     Selected = v.Equals(Model),
                     Text = v.GetDisplayName(),
                     Value = v.ToString()
                 });
}
@Html.DropDownList("", values)

In Model

[DisplayName("نوع سند")]
[UIHint("Enum")]
public DocumentType DocumentType { get; set; }

解决方案

You can pass the class name to the EditorTemplate using AdditionalViewData.

In the main view

@Html.EditorFor(m => m.DocumentType, new { htmlAttributes = new { @class = "myclass" } })

and in the EditorTemplate

....
@Html.DropDownListFor(m => m, values, ViewData["htmlAttributes"])

However including the logic for the SelectList in an EditorTemplate is not good practice. I would recommend your consider creating an extension method for generating the SelectList and then this EditorTemplate wont be required. Refer this example. And Selected = v.Equals(Model), is pointless because the Selected property will be ignored (the selected item will be the value of DocumentType)

这篇关于在MVC中添加类EditorFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆