Can you overload controller methods in ASP.NET MVC?

前端 未结 17 1682
无人共我
无人共我 2020-11-22 08:10

I\'m curious to see if you can overload controller methods in ASP.NET MVC. Whenever I try, I get the error below. The two methods accept different arguments. Is this some

17条回答
  •  逝去的感伤
    2020-11-22 08:44

    I needed an overload for:

    public ActionResult Index(string i);
    public ActionResult Index(int groupId, int itemId);
    

    There were few enough arguments where I ended up doing this:

    public ActionResult Index(string i, int? groupId, int? itemId)
    {
        if (!string.IsNullOrWhitespace(i))
        {
            // parse i for the id
        }
        else if (groupId.HasValue && itemId.HasValue)
        {
            // use groupId and itemId for the id
        }
    }
    

    It's not a perfect solution, especially if you have a lot of arguments, but it works well for me.

提交回复
热议问题