我想我明白你在说什么。您想控制视图中的 Enum 使用哪个模板。
我将解释使用编辑器模板,但如果您使用显示模板,它的工作方式相同。您应该能够遵循并申请您的方案。
这个想法是使用编辑器 html 助手的重载。
public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName);
它是这样称呼的
@Html.Editor("{property name}", "{template name}").
下面是一个例子来展示它正在被使用。
假设我们有这个枚举
public enum MyItems
{
Item1 = 1,
Item2 = 2,
Item3 = 3
}
这个帮手
public static class MyEnumHelper
{
public static List<MyItems> GetAllItems()
{
return new List<MyItems>()
{
MyItems.Item1,
MyItems.Item2,
MyItems.Item3
};
}
public static List<MyItems> GetSomeItems()
{
return new List<MyItems>()
{
MyItems.Item1,
MyItems.Item2
};
}
}
这个控制器
public class HomeController : Controller
{
public ActionResult AllItems()
{
return View();
}
public ActionResult SomeItems()
{
return View();
}
}
我们有这 2 个编辑器模板,它们放在 views/shared/editortemplates
第一个名为 MyItems.cshtml 是全部
@model MyItems?
@{
var values = MyEnumHelper.GetAllItems().Cast<object>()
.Select(v => new SelectListItem
{
Selected = v.Equals(Model),
Text = v.ToString(),
Value = v.ToString()
});
}
@Html.DropDownList("", values)
第二个叫做 MyItems2.cshtml 这是一些
@model MyItems?
@{
var values = MyEnumHelper.GetSomeItems().Cast<object>()
.Select(v => new SelectListItem
{
Selected = v.Equals(Model),
Text = v.ToString(),
Value = v.ToString()
});
}
@Html.DropDownList("", values)
然后在 AllItems.cshtml 中获取我们需要的调用的 MyItems.cshtml 模板
@model MyItemsViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.MyItem)
<submit typeof="submit" value="submit"/>
}
并在 SomeItems.cshtml 中通过调用 MyItems2.cshtml 来获取我们使用的一些项目
@model MyItemsViewModel
@using (Html.BeginForm())
{
@Html.Editor("MyItem", "MyItems2") @* this bit answers your question *@
<submit typeof="submit" value="submit" />
}