0

I'm trying to overload the method below because I don't want to pass a null for the optional parameter. So I read online that I could let overloads call each other. I was following this example:

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");
    }

I would like one method to take the optional parameter int? testID and the other method to not take the optional parameter. How can I do this?

Any help is very much appreciated it.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
coffeetime
  • 121
  • 2
  • 6
  • 14
  • why so difficult? You can have one method that takes `employeeID` and another that takes `testID` and `employeeID` ... I don't see any reason of having optional parameter – demo Mar 04 '19 at 18:04
  • Possible duplicate of [Can you overload controller methods in ASP.NET MVC?](https://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc) – Peter B Mar 04 '19 at 18:09
  • @PeterB That's only a duplicate if you take this question literally instead of showing the OP what should be done – Camilo Terevinto Mar 04 '19 at 18:10
  • By the way, this code doesn't compile: `excel.CreateExport(int employeeID);` – Camilo Terevinto Mar 04 '19 at 18:11

1 Answers1

4

If you don't want to pass null, default to null instead. Following the below structure, you can pass in an employeeID and a testID if needed. You only need this method (and not two).

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