我有以下几个 Enum
的结构:
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
}
还有一些其他的。所有这些都映射到 Entity Framework 属性和相关的“其他”属性:
public PersonEnums.Title Title { get; set; }
public string TitleOther { get; set; }
public string GetTitle => Title == PersonEnums.Title.Other ? TitleOther : Title.ToString();
现在,对于 View ,我不确定将这些组合到一个控件/部分/编辑器模板中的最简洁/最简单的方法?
我试过:
添加 View 模型:
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)
我在 @Html.EnumDropDownListFor()
行收到以下错误 Return type 'System.Enum' is not supported.部分
显示模板
@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>
我收到以下错误Templates can be used only with field access, property access, single-dimensional array index, or single-parameter custom indexer expressions.调用时EditorFor
对于如何最好地将通用 Enum
与 string
其他值一起转换为某种模板,我有点迷茫。使某些东西可用于此设置的最佳方法是什么?
显示和隐藏“其他”框的 javascript 很简单,它只是让所有内容正确映射回我一直坚持使用的 EF。
最佳答案
感谢@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);
}
所以我可以在我的 Razor View 中使用:
@Html.EnumWithOther(Model.Title, Model.TitleOther)
帮助将输出的 HTML 的默认 id
和 name
属性覆盖为正确的值,以便表单回发并在提交时正确映射。
此时,您仍然需要处理 JavaScript 部分以根据需要显示和隐藏“其他”文本框。
关于c# - 枚举和文本框组合的 MVC5 部分或编辑器模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180434/