3

At _Layout.cshtml used by all pages, when any background image is selected, I want to display the selected picture. But, I dont ,unfortunately, know how to pass this data to _Layout.cshtml.

AT _Layout.cshtml

<style type="text/css">
        #body-bg {
            background-image: url('//I want to change here');
        }
</style>

How should i do? From any controller, this data should be pass to _Layout.cshtml but how?

pinyil
  • 47
  • 1
  • 3
  • 9
  • 1
    You can using a base view model containing the property, or pass it using `ViewBag` or `ViewData` –  Aug 28 '17 at 00:23
  • Depending on how your handling it, you could use a template with a default value there as well. (ie. `@RenderSection(...)`) – AJ X. Aug 28 '17 at 00:24

1 Answers1

1

The most robust way is using a base viewmodel class and put a string property to hold image path:

Model Class

public class BaseViewModel
{
    public string BackgroundImage { get; set; }
}

_Layout.cshtml

@model BaseViewModel
<!DOCTYPE html>
<html>
<head>
     <!-- other styles, meta tags, etc. -->
     <style type="text/css">
     #body-bg {
         background-image: url('@Model.BackgroundImage');
     }
</head>
<body>
     <!-- body part -->
     @RenderBody()
</body>
</html>

If you're using relative path (e.g. ~/Images/Selected.png) instead of absolute path to refer image paths, use UrlHelper.Content with string property as argument:

#body-bg {
     background-image: url('@Url.Content(Model.BackgroundImage)');
}

Also don't forget to set viewmodel's string property inside controller action method:

public class HomeController : Controller
{
    // other stuff
    return View(new BaseViewModel { BackgroundImage = "/path/to/image.png" });
}

NB: You can use ViewBag or ViewData besides a viewmodel (they're both automatically passed to view), by changing Model to ViewBag/ViewData:

// View (CSS)
#body-bg {
    background-image: url('@ViewBag.BackgroundImage');
}

// Controller
public class HomeController : Controller
{
    // other stuff
    ViewBag.BackgroundImage = "/path/to/image.png";
    return View();
}

Note that ViewBag is dynamic, possibly extra check required to prevent NullReferenceException thrown when using ViewBag property.

References:

Passing Data to Views (MS Documentation)

Pass data to layout that are common to all pages

Passing Data to a Layout Page

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61