0

Currently, I am able to refer to body tag using code-behind during page load event in ASP.NET Webforms with this code here:

HtmlGenericControl body = (HtmlGenericControl)this.Master.FindControl("body1");
body.Style["background-image"] = Page.ResolveUrl("~/images/somepic.jpg");
body.Style["background-position"] = "0px 0px";
body.Style["background-repeat"] = "no-repeat";

I am wondering if this is achievable with ASP.NET MVC? Many thanks in advance.

3
  • What version of ASP.NET MVC are you using? Commented Aug 16, 2020 at 7:38
  • And is there a reason you can't just have these style properties set in normal CSS? Commented Aug 16, 2020 at 7:39
  • MVC 5, not MVC core. Why am I doing this is because I want to load the image dynamically based on condition. Thanks Commented Aug 16, 2020 at 7:41

1 Answer 1

2

Add the style rules as a String value to your View-Model class and then render it inside your view:

class MyViewModel
{
    public String BodyStyle { get; set; } = @"background-repeat: no-repeat; background-position: 0 0;";
}
@model MyViewModel

<body style="@( this.Model.BodyStyle )">

</body>

But style rules really shouldn't be set directly on elements, you should use CSS in stylesheets or a <style> element instead, and if styling <body> is page-specific, then use a class="" on <body> or <html> instead, like so:

class MyViewModel
{
    public String BodyClass { get; set; } = "foobar";
}
@model MyViewModel
<html>
<head>
    <style type="text/css">
body {
}

body.foobar {
    background-image: url("@Url.Content("~/images/somepic.jpg")");
    background-position: 0 0;
    background-repeat: no-repeat;
}
    </style>
</head>
<body class="@( this.Model.BodyClass )">

</body>

As these are being applied to your <body> element which is likely inside your _Layout.cshtml (rather than being in every .cshtml file) you'll need to use a common view-model interface and dereference that in your _Layout.cshtml:

MyViewModel.cs

interface ICommonPageViewModel
{
    String BodyClass { get; }
}

class MyViewModel : ICommonPageViewModel
{
    public String BodyClass { get; set; }
}

_Layout.cshtml

@{
    ICommonPageViewModel cvm = (ICommonPageViewModel)this.Model;
}
<html>
<head>
    <style type="text/css">
body {
}

body.foobar {
    background-image: url("@Url.Content("~/images/somepic.jpg")");
    background-position: 0 0;
    background-repeat: no-repeat;
}
    </style>
    @RenderSection("head")
</head>
<body class="@( cvm.BodyClass )">
    @RenderBody()
</body>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.