Asp.net 基于枚举值的渲染操作

Asp.net 基于枚举值的渲染操作,asp.net,asp.net-mvc,razor,enums,partial-views,Asp.net,Asp.net Mvc,Razor,Enums,Partial Views,在MVC5控制器中,我有一个ActionResult,它将根据用户的选择显示不同的报告。我按如下方式做,没有错误 主控制器: // POST: Report Init [HttpPost] public ActionResult ShowReport(ReportUserInput userInput) { return View(userInput); } ShowReport.cshtml[查看文件]: @model App.Repo

在MVC5控制器中,我有一个ActionResult,它将根据用户的选择显示不同的报告。我按如下方式做,没有错误

主控制器:

    // POST: Report Init
    [HttpPost]
    public ActionResult ShowReport(ReportUserInput userInput)
    {
        return View(userInput);
    }
ShowReport.cshtml[查看文件]:

@model App.ReportUserInput

<h2>ProjectBasedReport</h2>
@if(Model.rep_type == EnumOldReportTypes.ByGender)
{
    Html.RenderAction("ByGender", Model);
}
else if (Model.rep_type == EnumOldReportTypes.ByAddress)
{
    Html.RenderAction("ByAddress", Model);
}...

首先,使动作名称与
枚举
的枚举数名称相同。然后只需编写以下代码,而不是多个if/else:

Html.RenderAction(Model.rep_type.ToString(), Model);
或者,即使无法匹配
枚举
和操作名称,也可以使用
字典
枚举
映射为正确的操作名称:

var reportTypesActions=new Dictionary<EnumOldReportTypes, string> 
{ 
    { EnumOldReportTypes.ByAddress, "ActionNameOfByAddress" }, 
    { EnumOldReportTypes.ByGender, "ActionNameOfByGender" } 
};

我认为你的问题没有现成的解决办法。你最好的选择可能是定义你自己的助手。或者,您可以对枚举成员的自定义属性进行一些处理,但这听起来更像是一种恶意攻击,您需要在某个地方使用
if-else
,无论是在控制器中,还是在HtmlHelper扩展方法的视图中
var reportTypesActions=new Dictionary<EnumOldReportTypes, string> 
{ 
    { EnumOldReportTypes.ByAddress, "ActionNameOfByAddress" }, 
    { EnumOldReportTypes.ByGender, "ActionNameOfByGender" } 
};
Html.RenderAction(reportTypesActions[Model.rep_type], Model);