2016-05-12 52 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部分以根據需要顯示和隱藏「其他」文本框。