Swap background image from Asp . Net MVC page dynamically

Asked

Viewed 303 times

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.

2 answers

2

Using Jquery put this script in _Layout.cshtml.

<script>
    $(document).ready(function() {
        var i = Math.floor(Math.random() * 9) + 1;
        $("body").css("background-image", "url(/Background/Fundo (" + i + ").jpg);");
    }); 
</script>
  • Good morning Augusto. Thanks for the help. I put the script, but it does nothing. Where to put it to be triggered?

  • @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.

2

Dear friends, good morning.

I’ve already solved my problem.

   <script type="text/javascript">
    function Trocar() {
        $(document).ready(function () {
            var oBody = document.getElementById('myBody');
            var i = Math.floor(Math.random() * 9) + 1;
            oBody.style.backgroundImage = "url('../images/Foto" + i + ".jpg')";              
        });
    }
</script>

Grateful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.