views:

234

answers:

4

Hello,

I have a controller that is being called twice from an ActionLink call.

My home page has a link, that when clicked calls the Index method on the Play controller. An id of 100 is passed into the method. I think this is what is causing the issue. More on this below.

Here are some code snippets:

Home page:

<%= Html.ActionLink(“Click Me”, "Index", "Play", new { id = 100  }, null) %>

Play Controller:

public ActionResult Index(int? id)
{
        var settings = new Dictionary<string, string>();

        settings.Add("Id", id.ToString());

        ViewData["InitParams"] = settings.ToInitParams();

        return View();
}

Play view:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

(html <head> omitted for brevity)

<body>
    <form id="form1" runat="server" style="height:100%">

Hello

    </form>
</body>

If I get rid of the parameter to the Index method, everything is fine. If I leave the parameter in place, then the Index method is called with 100 as the id. After returning the View, the method is called a second time with a parameter of null.

I can’t seem to figure out what is triggering the second call.

My first thought was to add a specific route like this:

routes.MapRoute(
    "Play", // Route name
    "Play/{id}", // URL with parameters
    new {controller = "Play", action = "Index"} // Parameter defaults
    );

This had no effect other than making a prettier looking link.

I am not sure where to go from here.

Thank you in advance.

Rick

A: 

Try changing the int? id to int id. It's matching the route the 2nd time because you're calling the index again with a null id.

Lester
A: 

You can also try changing your route to this.

routes.MapRoute( 
    "Play", // Route name 
    "Play/{id}", // URL with parameters 
    new { controller = "Play", action = "Index" , id = "" } // Parameter defaults 
);
Mike Geise
+3  A: 

Is there any other markup that could be accidentally referencing the page? Script references, image references, css references, all could be mistakenly pointed at '.' or the current page.

Frank Schwieterman
this is probably the culprit.
Mike Geise
It turned out that a javascript "could not find file" error was causing the page to load twice. Thanks!
rboarman
I had the same issue. In my case it was an <img> tag with src="", so that I could load an image dynamically later. Took quite a bit of effort to track that one down. Fix was to remove the src attribute completely.
Darren Oster
+1  A: 

You can step through the code in your view. Step through and see where the second call comes from.

Alistair