dumbchemistry
dumbchemistry

Reputation: 403

Putting a value from model into an HTML style attribute via Razor

I'm trying to display a series of divs in my view, the width of each being dependent on the amount of items in a child list in my viewmodel. I'm determining what the width of the divs ought to be in my controller and am trying to alter the width of the divs in my view by changing the value of the HTML style attribute. However, I can't seem to insert a value from my model into a style attribute in the same way I can insert it into a class attribute. Here's a little bit of my code:

@for (int i = 0; i < Model.IntegrationActivityList.Count; i++)
{
    <div data-integration-id="@Model.IntegrationActivityList[i].WorkflowIntegrationActivityParentId" style="width:@Model.IntegrationActivityList[i].IntegrationActivityDivWidth;">
        /* more code here, iterate through child list items */
    </div>
}

data-integration-id="@Model.IntegrationActivityList[i].WorkflowIntegrationActivityParentId" works fine, but style="width:@Model.IntegrationActivityList[i].IntegrationActivityDivWidth;" does not result in a rendered style attribute at all.

I've tried a couple other methods, such as using Html.Raw to generate the markup, also to no avail: <div @Html.Raw("style='width: " + Model.IntegrationActivityList[i].IntegrationActivityDivWidth + ";'")>.

How can I modify the width of my div using Razor and information from my model? (I'm also open to any other suggestions on better ways to accomplish this.)

Upvotes: 0

Views: 3293

Answers (1)

dumbchemistry
dumbchemistry

Reputation: 403

I was able to fix this issue by adding the @Html.Raw() function call inside the style attribute like so:

<div style="@Html.Raw("width:" + Model.IntegrationActivityList[i].IntegrationActivityDivWidth + ";")"></div>

Upvotes: 2

Related Questions