Share via


How to set css class to div dynamically in mvc view?

Question

Thursday, June 1, 2017 9:12 AM

hello,

I am not getting how to do this, let me explain, I have data base having column name SignalCSS having some row (css class name) like PT1, PT2 . . . , 

now, in my model class I have property say public string SignalCSS{get;set} in this property  I am getting class name, and I have .css file in that I define my class ex.

.PT1{ background : red}

.PT2{background : green}

now, in my view i have foeach loop, where i am creating div

foreach

{

<div class=" ? "></>

}

if my property value is PT1 then I want div with red background

if it is PT2 then it shoud be green.

So how can I achieve this, I am doing my first project in mvc, please help me to get out

thanks

tink

All replies (4)

Thursday, June 1, 2017 9:51 AM âś…Answered

You can also add CssClass property into your object's class, so  you will just write

<div class="@item.CssClass"></div>

Thursday, June 1, 2017 9:26 AM

It is easy:

@foreach (var item in this.Model.Items)
{
  if (item.Property == "PT1")
  {
    <div class="red"></div>
  }
  else
  {
    <div class="green"></div>
  }
}

Or even more simple:

@foreach (var item in this.Model.Items)
{
  <div class="@((item.Property == "PT1") ? "red" : "green")"></div>
}

Thursday, June 1, 2017 9:49 AM

Thanks Dmitry for responce, 

but I have more than 20(not fix) classes, and my dive size also big so this is not right solution, i think.

thanks 


Thursday, June 1, 2017 10:32 AM

cool!!!!!!!!!!

it works, thanks.