Alex
Alex

Reputation: 38529

Passing value for css from a nested Razor view, to Master view

I have a "master" view (_MasterLayout.cshtml)

This has a Div, with an ID of "main"

<div id="main" class="xxx">
</div>

In views that inherit from _MasterLayout.cshtml, I need to be able to set the value of the class in this div (for example, set it to "product-page")

How can I achieve this?

I've thought about using ViewBag, which would work -

ViewBag.MainDivCSS = "product-page";

However, this is a typo waiting to happen.

Are there any better ways of doing it?

Upvotes: 0

Views: 381

Answers (1)

archil
archil

Reputation: 39501

The best would be if you wouldn't have to set master page classes from child view page. For me, it'd be better to add one more div if this is all about nesting sections. Surround your whole child view with

<div id="child" class="product-page">

rest of child view here

</div> 

and you would get

<div id="main">
    <div id="child" class="product-page">

    rest of child view here

    </div> 
</div>

but anyways, if you want to, one option is to do that in single place in child view via js

<script>
     $(function(){
          $('#mainc').addClass('product-page');
     });
</script>

I do not like making strongly view specific data carried by view models and managed by controller, so i prefer javascript approach in this case. And definitely, you're right, you should not use ViewBag.

Upvotes: 1

Related Questions