Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# strings as html attributes

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.

like image 852
Christian4423 Avatar asked Dec 23 '22 20:12

Christian4423


2 Answers

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>
like image 56
Darin Dimitrov Avatar answered Dec 28 '22 05:12

Darin Dimitrov


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?

like image 40
maccettura Avatar answered Dec 28 '22 05:12

maccettura