Can we overload MVC controller action methods? [du

2019-06-04 02:39发布

问题:

This question already has an answer here:

  • Can you overload controller methods in ASP.NET MVC? 16 answers

I was trying to overload controller method or action I am able to write controller action and compile but still I am not getting result.

   public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
    public ActionResult Contact(string str)
    {
        ViewBag.Message = "Your contact page by overloaded method";

        return View();
    }

but still I am getting following Error Server Error in '/' Application

回答1:

You get the conflict because because string is nullable.

You can use [ActionName("NewActionName")] to give a different action name by leaving the method name intact.

You shouldn't get conflict if you have another action method like this

public ActionResult Contact(int Value)

But, below action will again fail

public ActionResult Contact(int? Value)

The reason is obvious. The parameter is again nullable.