Reputation: 749
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.
Upvotes: 0
Views: 90
Reputation: 155045
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
:
interface ICommonPageViewModel
{
String BodyClass { get; }
}
class MyViewModel : ICommonPageViewModel
{
public String BodyClass { get; set; }
}
@{
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>
Upvotes: 2