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=""width:" 20%;"="">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.
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>
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With