2016-05-12 25 views
2

我有几个Enum S的结构如下:用于枚举和文本框组合的MVC5部分或编辑器模板?

public Enum Title 
{ 
    Unknown = 0, 
    Mr = 1, 
    Mrs = 2, 
    ... 
    Other = -1 
} 

public Enum Title 
{ 
    Unknown = 0, 
    Mr = 1, 
    Mrs = 2, 
    ... 
    Other = -1 
} 

public enum MaritialStatus 
{ 
    Unspecified = 0, 
    Single = 1, 
    Married = 2, 
    Separated = 3, 
    Divorced = 4, 
    ... 
    Other = -1 
} 

而其他一些人。所有这些映射到实体框架特性和相关的“其他”属性:

public PersonEnums.Title Title { get; set; } 
public string TitleOther { get; set; } 
public string GetTitle => Title == PersonEnums.Title.Other ? TitleOther : Title.ToString(); 

现在,我不能确定的清洁/最简单的方法让这些组合成一个控制视图/分/编辑模板?

我已经试过:

添加视图模式:

public class EnumWithOtherViewModel 
{ 
    public Enum Enum { get; set; } 
    public string OtherValue { get; set; } 
} 

部分

@Html.Partial("_EnumWithOther", new EnumWithOtherViewModel { Enum = Model.Title, OtherValue = Model.TitleOther }) 

_EnumWithOther.cshtml

@model RS3.Models.EnumWithOtherViewModel 
@Html.EnumDropDownListFor(m => m.Enum, new { @class = "form-control EnumWithOther" }) 
@Html.EditorFor(m => m.OtherValue) 

我收到以下错误返回类型'System.Enum'不受支持。上在部分

显示模板的@Html.EnumDropDownListFor()线

@Html.EditorFor(m => new EnumWithOtherViewModel { Enum = m.Title, OtherValue = m.TitleOther }) 

EnumWithOther.cshtml

@model EnumWithOtherViewModel 
<div class="form-group"> 
    @Html.LabelFor(m => m, new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EnumDropDownListFor(m => m.Enum, new { @class = "form-control EnumWithOther" }) 
     @Html.ValidationMessageFor(m => m.Enum, "", new { @class = "text-danger" }) 
     @Html.EditorFor(m => m.OtherValue) 
    </div> 
</div> 

我得到以下错误模板可以只用领域中使用的访问,属性访问,单维数组索引,o r单参数自定义索引器表达式。调用EditorFor

时,我有点失落,以如何更好地过去一个通用Enum成某种类型的模板,用string其他值一起。什么是使这个设置可重用的最佳方式?

显示和隐藏“其他”框的JavaScript是微不足道的,它只是让所有东西都能正确地映射回EF,而我坚持使用它。

+1

关于你的第二选择,使​​用编辑器模板,你有没有试过newing了EnumWithOtherViewModel在上一行,然后使用该变量在lambda? – ngm

+0

良好的通话 - 刚刚试了一下,它并编译但'EnumDropDownFor'现在只需与价值文本框,和ID是不正确......所以,我不认为这是正确的路线走下来... – RemarkLima

+1

不知道你为什么得到一个文本框的枚举。至于id是不正确的,如果你的意思是呈现的html中的id属性 - 你最好在你的主模型上有一个EnumWithOtherViewModel类型的属性,然后调用EditorFor,在你的视图中动起来。 – ngm

回答

0

感谢@ngm让我走上了正确的道路。看起来最清洁的方式是使用HTML助手。

public static MvcHtmlString EnumWithOther<TModel, TEnum>(this HtmlHelper<TModel> html, TEnum e, string other) 
{ 
    string r = string.Empty; // Setup the return holder 
    string label = e.GetType().Name; // Get the name of the Enum for the ID's 
    r += html.EnumDropDownListFor(m => e, new { @id = label, @Name = label, @class = "form-control EnumWithOther" }); // Setup the dropdown for the enum 
    r += html.TextBoxFor(m => other, new { @id = $"{label}Other", @Name = $"{label}Other" }); //Setup the textbox for other 
    return new MvcHtmlString(r); 
} 

所以我可以在我的剃刀视图使用:

@Html.EnumWithOther(Model.Title, Model.TitleOther) 

帮助覆盖默认的输出HTML的idname属性的正确值的形式被调回并正确映射提交。

此时,您仍然需要处理JavaScript部分以根据需要显示和隐藏“其他”文本框。