1
I’ve been doing some research, but I can’t get anything to say about it. I had done it before, in Web Forms, but in MVC I hadn’t needed it yet. I need to change the background image of the page every time it loads. For example: I have 10 images, and at each _layout.cshtml load, this would have to be loaded with one of the 10 images. Doing the Random and picking up the image is easy, the problem and how to apply the style. In Web Forms it was easy, because I had the code where I created the method and called in the Page load. Only in MVC, I don’t have load.
Method used in Web Forms:
public static void ChangeBGs(HtmlControl oMainBody)
{
Random voRandom = new Random();
int vi = voRandom.Next(1, 10);
oMainBody.Attributes.Add("style", $"background-image: url('/Background/Fundo ({vi}).jpg')");
}
In this method, I can change the Body style of the page, because in WF, I have access.
How to do something similar in MVC, more specifically in _Layout.cshtml. If I have how to apply the style already created, and just keep changing it would also be interesting.
Grateful.
Good morning Augusto. Thanks for the help. I put the script, but it does nothing. Where to put it to be triggered?
– Fernando M. Davanzo
@Fernandom.Davanzo. Are you using Jquery? Check the line
<script src="https://code.jquery.com/jquery-3.3.1.js" type="text/javascript"></script>
is present in your layout.– Augusto Vasques