Add a style to an element based on model value

I want to add a simple inline style to my div tag if certain criteria are met.

I can apply the disabled class successfully, but I cannot get my cursor style to display.

<div class="item @(item.AvailableTimeSlots == "0" ? "disabled" : "")" @(item.AvailableTimeSlots == "0" ? "style='cursor: default;'" : "")> 

any pointers?

+4
source share
2 answers

Working snippet

 <div class="item @("0" == "0" ? "disabled" : "")" @Html.Raw("0" == "0" ? "style='cursor: default;'" : "")> 

Adding Html.Raw() fixed the problem for me. Without this, you will get something like:

 <div class="item disabled" style=&#39;cursor: default;&#39;> 

I tried several different browsers, and each of them gave different results when checking the DOM. IE8 controls it; Chrome incorrectly reinstalls it; IE9 seems to make it well-formed correctly.

A few notes:

  • @James's solution, which removes inline styles, is a good one. Current code is really hard to read, and inline styles are rarely a good idea.
  • It looks like item.AvailableTimeSlots should be an integer, not a string.
+2
source

Any pointers?

It is always best to avoid inline styles whenever possible. I would advise you to move your cursor code into your own CSS class and work exclusively with classes, for example.

CSS

 .default { cursor: default; } .disabled { ... } 

View

 @{ var itemCLass = @item.AvailableTimeSlots == "0" ? "disabled" : "default"; } <div class="item @itemClass" /> 
+2
source

Source: https://habr.com/ru/post/1442749/


All Articles