【问题标题】:How to overload controller method in MVC?如何在 MVC 中重载控制器方法?
【发布时间】:2019-03-05 02:12:26
【问题描述】:

我正在尝试重载下面的方法,因为我不想为可选参数传递 null。所以我在网上读到我可以让重载互相调用。我正在关注这个例子:

Is passing null in to a method acceptable

[HttpGet]
    public ActionResult TesMethod (int? testID, int employeeID)
    {
        Excel excel = new Excel();
        excel.CreateExport(null, int employeeID);
        return RedirectToAction("Index", "Employee");
    }

[HttpGet]
    public ActionResult TesMethod (int employeeID)
    {
        Excel excel = new Excel();
        excel.CreateExport(int employeeID);
        return RedirectToAction("Index", "Employee");
    }

我想要一种方法来获取可选参数 int? testID 和其他不采用可选参数的方法。我该怎么做?

非常感谢任何帮助。

【问题讨论】:

  • 为什么这么难?您可以有一种方法采用employeeID,另一种采用testID 和employeeID ...我看不出有任何理由有可选参数
  • @PeterB 如果你从字面上理解这个问题而不是向 OP 展示应该做什么,那只是重复
  • 顺便说一句,这段代码无法编译:excel.CreateExport(int employeeID);

标签: c# asp.net-mvc overloading


【解决方案1】:

如果您不想传递 null,则默认为 null。按照以下结构,如果需要,您可以传入 employeeID 和 testID。你只需要这个方法(而不是两个)。

[HttpGet]
public ActionResult TesMethod (int employeeID, int? testID = null)
{
    Excel excel = new Excel();
    excel.CreateExport(testID, employeeID);
    return RedirectToAction("Index", "Employee");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2017-11-07
    相关资源
    最近更新 更多