MVC controller is being called twice
Asked Answered
K

21

47

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.

Kappenne answered 1/5, 2010 at 18:43 Comment(1)
Can you check in firebug if the URL is requested twice?Bonni
P
70

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.

Patio answered 1/5, 2010 at 21:27 Comment(9)
It turned out that a javascript "could not find file" error was causing the page to load twice. Thanks!Kappenne
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.Joke
Some browsers will look for the /favicon.ico file which may cause the routes to be run again.Janellajanelle
Mine was because I was trying to use a model in my layout page instead of creating a new model and passing it into a partial view.Irrawaddy
I had $.ajax( ); in my JavaScript for some reason. Removed it and happy happy happy.Sands
Mine was empty background image url: style="background-image: url(); width:150px; height: 150px;"Aspa
Mine was the result of a malformed a tag. Someone had accidentally written <a/> instead of </a>, leading to all sorts of wackiness.Clermontferrand
Whooaaa! It was favicon!!! Starting from Visual Studio default project, the default code was looking for a PNG while it was an ICO!!!!! This created a double call that forced antiforgery to fail!!!Necessity
I had the same issue because of importing script file twice, in the Layout and in the view itself : )Enculturation
L
11

10 hours chasing that bug in a Java Spring Maven project.

First on SELECT I thought Hibernate was just logging twice, but then with INSERT I thought requests were called twice. Stepping throught the code I discovered controller was called twice...

Tried all possible Spring configuration, thinking the context was loaded twice or a bean was instantiate twice...

In despair, rebuilded the project piece by piece to finally add a fragment of HTML and kaboom bug's back.

<img alt="" src="#" />

The sharp sign was guilty, reloading the URL. I know the topic is old, but I summarized my searchs with the words I used to look for in vain on Internet to find an answer to the same issue! Could help others...

Lateen answered 15/6, 2017 at 9:29 Comment(2)
I ran into the same with where src was simply empty instead of the hash: <img src='' /> Same result. Tried to "load" the image resulting the same controller action to be called twice.Rue
I had <link rel="shortcut icon" href="#">Kamalakamaria
A
4

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

Auricular answered 2/5, 2010 at 0:49 Comment(1)
This worked for me after a #headscratch moment of confusion. Turns out I was re-routing a login form, and on that reroute, I was setting a new view, with the same layout again, forcing it to render twice. Search for MasterName, and see where you may be forcing the layout name.Breton
Z
4

While debugging I found out that a Partial View causes the the Controller to be called a second time. It sucks, but I don't see a work around that one.

Zelig answered 11/12, 2014 at 22:15 Comment(1)
If you have any script/css file reference inside the partial view, you must remove it.Polyclinic
G
4

there should be a html markeup that is not working properly. please check all img tage. also check

<link rel="icon" href="favicon.ico" type="image/x-icon" />
Giroux answered 20/8, 2015 at 9:23 Comment(0)
C
1

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.

Cargile answered 1/5, 2010 at 18:49 Comment(0)
A
1

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 
);
Anecdotic answered 1/5, 2010 at 21:24 Comment(0)
L
1

I had this same issue and verified all the possible suggestions but no luck then I noticed following JS warning message in my Console.

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

xmlHttp = new XMLHttpRequest();

I corrected this and it works for me.

Take care all your js errors and warning messages.

This may help to someone.

Lello answered 2/8, 2016 at 16:17 Comment(2)
Got the same warning message. How did you fix it?Equator
Yes Siva right, this is a bored case. If it couldn't find the image looking to home controller interesting with seo engine optimization with boilerplate static filesAllgood
J
1

Something very stupid I did...had 2 Forms on a page with one button on each form. I had added script to submit a specific form based on the button clicked but, since the default action of a button on a form is to do a submit, it called my Controller Action twice. :^(

    $('#SaveButton').click(function (event) {
        $("#AttendanceDetailForm").submit();
    });
Jodyjoe answered 18/10, 2016 at 22:41 Comment(2)
I inherited a JSP page that did the same thing. I changed the buttons from type="submit" to type="button" (and kept the .submit() functions in the JavaScript) and voila, only a single call to the controller. Had I not seen this, I would still be looking for why I kept getting getOutputStream() has already been called for this response exceptions.Flacon
FYI - the problem is the JS on this response is the event.PreventDefault() was not called, nor did the function return false. Therefore it submitted the form twice, once with code and a second time by virtue of that is what forms do. However, if that is all the JS did and #SaveButton was an input of type="submit" the JS was unnecessary anyway.Vanthe
S
1

It was old, but some one will need it. My problem is style="background-image: url(../) . Let's find html, css code about this style

Seaborne answered 6/1, 2021 at 4:12 Comment(0)
A
0

I was also facing the same issue. after thoroughly checking my project , i found none such empty reference case. Then i found out that it is caused by FireBug. Disabling firebug or using other browser which has not firebug installed solved the problem.

Anticoagulant answered 1/9, 2015 at 20:0 Comment(0)
T
0

My issue was resolved by making sure I wasn't double referencing my JavaScript files, which I was.

This was causing the action to be hit twice when I clicked the link.

I know the above has been said before but I thought I would point out that it's worth checking to see if your files are being loaded twice, especially if you're using Partial Views.

I noticed that in one of my Partial Views I was telling it to use the main layout page which contained the scripts that were responsible for what happened when I clicked on the links. So I fixed this by just setting layout = null; since it's a partial view anyway and is already being loaded inside of the main layout.

Thinner answered 30/9, 2016 at 15:13 Comment(0)
C
0

In my case, I was using a Partial View (so no Form tags) and using an on click handler in JQuery to call a method in the controller via Ajax. But I had declared the button the handler was attached to as type Submit. I forgot to pass in e to my handler function so as to call e.PreventDefault()!! So the Controller method was being called twice - once from an ajax call and once for Submit. The 2nd time around the parameters were null. This caused me so much grief. Such a small thing. So small that it was easily overlooked. Hope this helps someone else.

Catatonia answered 7/12, 2016 at 18:55 Comment(0)
H
0

In my case it was incorrectly configured remote script Yandex.metrika (Google analytics analog). This script was presented on each page, so any controller and any action was called twice. Check your Ya.metrika settings for more details.

Ha answered 26/10, 2017 at 18:27 Comment(0)
M
0

This is an old question and some answers are still useful. That is why I am adding a new answer, hoping that will help someone else. For me, I have an app that redirects users back and forth between my domains. Due to some of my recent HttpCookie related work, I had added below line of code:

httpCookieObject.SameSite = SameSiteMode.Strict;

Turns out the SameSiteMode.Strict causes issues when it comes to cross-origin authentication schemes. This is Microsoft documentation about it: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2

To strictly enforce a same-site policy of SameSiteMode.Strict, set the MinimumSameSitePolicy. Although this setting breaks OAuth2 and other cross-origin authentication schemes, it elevates the level of cookie security for other types of apps that don't rely on cross-origin request processing.

So, my solution was that I do not use the SameSiteMode.Strict policy and I am good to go.

Michaud answered 18/7, 2019 at 18:2 Comment(0)
C
0

I was chasing my problem and found it in here:

Had <div style="width: 200px; height: 200px; background-image: url('\Asd\image.jpg')"></div> and problem made \ character so inside server side code i replaced all \ with / and it is working as charm.

Candleberry answered 24/6, 2020 at 10:4 Comment(0)
R
0

I also had the same problem. my problem was because of an add-on I installed in the browser.

Check out the add-ons in your browser.

Rhu answered 19/10, 2020 at 13:44 Comment(0)
B
0

I had same script reference in my View and the _Layout.cshtml. Removing the reference in either place resolved the issue

@Scripts.Render("~/bundles/jqueryval")
Bothnia answered 28/1, 2021 at 14:22 Comment(0)
I
0

I'm using ASP.NET MVC and got the same problem. In my _Layout.cshtml, there was a deprecated tag "bgsound". The problem got solved by replacing "bgsound" with "audio". I think some deprecated tags may cause the same problem.

Ingest answered 7/1, 2022 at 18:59 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Appressed
I
0

As far as I know, this issue can have three main reasons.

  1. You called the controller function twice from the client. That means: New Request => New Scope => New Controller Instance. So a debug mark in the controllers constructor should hint on a second call.

  2. You're calling twice from a middleware.

  class Middleware: IMiddleware {  
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        await next(context); //call #1
        await next(context); //call #2
        //This is tricky... base calls might also call the controller function, and those are easily overlooked!
        await base.InvokeAsync(HttpContext context, RequestDelegate next);
    }
  }

  1. You're calling twice from the controller itself:
  class SomeController: Controller {  
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
      await next();//call #1
      await next();//call #2
      //And again... tricky... base calls might also call the controller function, and those are easily overlooked!
      await base.OnActionExecutionAsync(context, next);
    }
  }

However, there might be more reasons to this issue, that i'm just not thinking about at the moment. The easiest way to indicate second calls within the same request, is to keep "stepping into" at the end of the first call. You will automatically end up at the second call at some point.

Iaverne answered 2/9, 2022 at 10:22 Comment(0)
T
0

In my case I had an extension installed on browser which led to all pages to run twice. The extension name is "torrent-scanner-popup". I cannot recognize I installed it.

To track it down I stared to remove all content from my page. And eventually when I removed everything! the page is still reloading twice!

enter image description here

Trimming answered 19/2 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.