Alberto Rubini
Alberto Rubini

Reputation: 655

Asp.Net MVC - Overload Action method

I created an asp.net mvc web site

My problem is how to implemented overload action method

Controller


    public ActionResult Index(int id)
    {
        //code
        return View(model);
    }

    public ActionResult Index()
    {
        //code  
        return View(model);
    }

View


    <div id="menucontainer">
            <ul id="menu">          
                    <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                    <%if (Page.User.Identity.IsAuthenticated)
                      {%>
                    <li><%= Html.ActionLink("Profilo", "Index", "Account")%></li>
                    <%} %>
                    <li><%= Html.ActionLink("About", "About", "Home")%></li>
                </ul>
            </div>

Usercontrol (ascx) inserted in the View. This usercontrol lists the friends of the profile (view)


   <td>
            <%= Html.ActionLink(Html.Encode(item.Nominativo), "Index", "Account", new { id = item.IdAccount }, null)%>
        </td>

Global asax


    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", 
                "{controller}/{action}/{id}", 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
            );
        }

when i click the action Index in the view, return the error "Can not find the resource... ecc.."

I found several answer for this problem (using attribute ecc..) but is not works.

There's a way to do that? I must add a maproute in a global asax?

thanks so much for your replies

Upvotes: 5

Views: 6645

Answers (1)

Max Toro
Max Toro

Reputation: 28618

You need to decorate both overloads with an ActionMethodSelector attribute for disambiguation. ASP.NET MVC does not know how to select the appropriate overload.

A workaround is to handle both actions in the same method:

public ActionResult Index(int? id) {

   if (id.HasValue) {
      // id present
   } else {
      // id not present
   }
}

Upvotes: 10

Related Questions