Kurt Wagner
Kurt Wagner

Reputation: 3315

How to Autosize Column Width in .CSHTML?

So in MVC I used the power of VS2013 to autogenerate a view off a list type which displays the list of objects and its properties in array format using foreach. How can modify the code to auto-size the column widths to fit?

<table class="table">
    <tr>
        <th align="center">
            @Html.DisplayNameFor(model => model.IsoCode)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th align="center">
            @Html.DisplayNameFor(model => model.Continent)
        </th>
        <th align="center">
            @Html.DisplayNameFor(model => model.CountryId)
        </th>
        <th align="center">
            @Html.DisplayNameFor(model => model.TotalLanguages)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td align ="center">
            @Html.DisplayFor(modelItem => item.IsoCode)
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td align ="center">
            @Html.DisplayFor(modelItem => item.Continent)
        </td>
        <td align ="center">
            @Html.DisplayFor(modelItem => item.CountryId)
        </td>
        <td align ="center">
            @Html.DisplayFor(modelItem => item.TotalLanguages)
        </td>
        <td>
            @*@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |*@
            @Html.ActionLink("Details", "Details", new { id = item.CountryId })
            @*@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })*@
        </td>
    </tr>
}

Upvotes: 1

Views: 6164

Answers (1)

Leo
Leo

Reputation: 14830

First, make sure there's enough space to show all the content in the table cells. If you are giving an explicit width to the table (e.g. using pixels as measurement units) you might be inadvertently restricting the space allowed for tbe table to render its contents. Here's what you can try

  • if an explicit width its set for the table or cells then remove it or use dynamic units such as percentage
  • set white-space nowrap for the table cells

Give it a go and see how it goes

Upvotes: 5

Related Questions