Search code examples
c#asp.net-mvcviewstack-overflow

Unhandled exception System.StackOVerflowException c#


I wrote a piece of code that returns a random string sponsorname from a list of sponsors. This sponsorname should be visible at each page, so I call the RandomSponsor method in the shared _layout view. This RandomSponsor method is based in the HomeController and has it's own view containing only a Html.Action

And at that Html.Action the program returns an error:

System.StackOverflowException {Cannot evaluate expression because the current thread is in a stack overflow state.}

This is my RandomSponsor method:

    [HttpGet]   
[ChildActionOnly]
public ActionResult RandomSponsor()
{
    var model = service.getRandomSponsor();
    return PartialView("RandomSponsor", model);
}

RandomSponsor.cshtml, where the programs stops

@Html.Action("RandomSponsor")

And my call in the shared layout page _Layout.cshtml:

@Html.Action("RandomSponsor", "Home")

While i'm debugging i noticed that the RandomSponsor method goes to it's view, but because my Html.Action requests the function again, it's stuck in a loop. I think I give the wrong parameter to the Html.Action in the RandomSponsor.cshtml view, but I dont know what is the correct one.

Does anyone had a similar problem or knows how to fix this error, i'm all ears.

Regards


Solution

  • You need to put the actual HTML that you want to child action to render in its view.

    It doesn't make sense to have the view recursively render its own action.