基于枚举值渲染动作

Render Action based on Enum Value

在 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);
}...

在这里它工作正常,我只关心 long if else,如何在没有 if 条件的情况下调用它们,例如:

HTML.%somefunction%

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

Html.RenderAction(Model.rep_type.ToString(), Model);

或者即使您无法匹配 enum 和操作名称,您也可以使用 Dictionary 将您的 enum 映射到正确的操作名称:

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

现在您可以编写以下代码:

Html.RenderAction(reportTypesActions[Model.rep_type], Model);