4

I am trying to make my razor view a little more dynamic. I am trying to set an inline style to TDs in a table.

I made the string:

@{
    double width = 100 / 5;
    String widthStyleString = String.Format("style=\"width: {0}%;\"", width);
}

That worked out great when I tested it as plain text. I got:

style="width: 20%;"

However when I tried to put it into an HTML element I got this:

<td class="table--td" style="&quot;width:" 20%;&quot;="">Some Value</td>

How would I get it to not parse the " as the entity? (it would not let me type & quot without making it into an actual ")


update:

This is still a good way to do HTML atrributes. However in THIS instance, it is a style tag, the people commenting are right; it is better to do it in css and not the logic. If you have this exact issue (style attribute), the stack post below will help you. Otherwise, Html.Raw() is good.

Equal sized table cells to fill entire width of holding table

That link will solve this issue if you DO NOT need to worry about IE8 and below. Otherwise you still have to hardcode the width percentage in your css.

Community
  • 1
  • 1
Christian4423
  • 1,746
  • 2
  • 15
  • 25

2 Answers2

8

You could use @Html.Raw because the @ function will HTML encode the output:

<td class="table--td" @Html.Raw(widthStyleString)>Some Value</td>

instead of:

<td class="table--td" @widthStyleString>Some Value</td>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

Look into @Html.Raw()

You could do something like this with what you currently have:

<td class="table--td" @Html.Raw(widthStyleString)>Some Value</td>

I would probably look into a better way of generating the string though. You could create your own Html helper that takes parameters of your style and your contents and then it outputs to the page. The benefit of this is your code is in one place (DRY).

Another thing to contemplate is the very fact you are using inline styles. Is there really no way you could leverage the power of CSS to accomplish what you want?

maccettura
  • 10,514
  • 3
  • 28
  • 35
  • You are right, Inline is bad practice but I am leaving it to this one exception.(besides display:none) I use CSS / Sass for all other styles but this needed to be dynamic and its a lot easier to have it done when I can get the percentage with quick math. I prefer to keep the logic separate from the view completely. I will need to look into making html helpers. I am new to the c# end of this and that would be a really cool part to understand. Thank you! – Christian4423 Feb 14 '17 at 15:34
  • 1
    [This](http://www.webdevelopmenthelp.net/2014/07/custom-html-helper-in-aspnet-mvc.html) is a pretty quick reference to help start you off – maccettura Feb 14 '17 at 15:35