ASP.NET MVC 6多属性对象表格宽度适配问题求助
ASP.NET MVC 6 表格过宽适配解决方案
我是ASP.NET MVC 6新手,已实现分页、列排序和搜索功能,用Bootswatch完成视图样式。当前问题:展示含大量属性(含最长500字符文本字段)的Order对象时,HTML表格过宽超出浏览器范围;属性少的对象显示正常。需在保留分页功能的前提下,实现表格宽度适配缩小。
解决方法
1. 启用Bootstrap响应式表格
给表格添加table-responsive容器,让表格在小屏幕支持横向滚动,同时不破坏页面整体布局:
<div class="table-responsive"> <table class="table" style="width:100%;"> <!-- 原有表格内容保持不变 --> </table> </div>
2. 控制长文本显示方式
针对Comments、Field1-Field4这类长文本字段,可选择以下两种处理方式:
方式A:自动换行
使用Bootstrap内置的text-wrap类,让文本自动换行以适应列宽:
<td class="text-wrap"> @Html.DisplayFor(modelItem => item.Comments) </td> <td class="text-wrap"> @Html.DisplayFor(modelItem => item.Field1) </td> <td class="text-wrap"> @Html.DisplayFor(modelItem => item.Field2) </td> <td class="text-wrap"> @Html.DisplayFor(modelItem => item.Field3) </td> <td class="text-wrap"> @Html.DisplayFor(modelItem => item.Field4) </td>
方式B:文本截断+悬停显示完整内容
自定义CSS样式限制列宽,超出部分用省略号代替,同时通过title属性让用户悬停时查看完整内容:
首先在视图头部添加样式:
<style> .text-truncate-custom { max-width: 150px; /* 可根据需求调整宽度 */ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style>
然后修改对应单元格:
<td class="text-truncate-custom" title="@Html.DisplayFor(modelItem => item.Comments)"> @Html.DisplayFor(modelItem => item.Comments) </td> <!-- Field1-Field4按同样方式修改 -->
3. 手动分配列宽
给表头和对应的单元格设置固定宽度,优先压缩长文本列,固定短内容列的宽度:
<thead> <tr> <th style="width:10%;">Proveedor</th> <th style="width:5%;">Pais</th> <th style="width:10%;">Categoria</th> <th style="width:10%;">Codigo Orden</th> <th style="width:8%;">Moneda</th> <th style="width:8%;">Monto</th> <th style="width:8%;">Fecha</th> <th style="width:8%;">Fecha Tope</th> <th style="width:10%;">Comprador</th> <th style="width:12%;">Comentarios</th> <th style="width:12%;">Campo 1</th> <th></th> </tr> </thead>
4. 可选:小屏幕隐藏次要列
使用Bootstrap响应式类,在小屏幕上隐藏非必要的列,保证核心信息展示:
<th class="d-none d-md-table-cell">Campo 3</th> <th class="d-none d-md-table-cell">Campo 4</th>
对应的单元格也要添加相同类:
<td class="d-none d-md-table-cell text-wrap"> @Html.DisplayFor(modelItem => item.Field3) </td> <td class="d-none d-md-table-cell text-wrap"> @Html.DisplayFor(modelItem => item.Field4) </td>
原代码参考
对象模型
public class Order { [Required] [Key] public int Id { get; set; } [ForeignKey("Id")] public int ProviderId { get; set; } public virtual Provider Provider { get; set; } = null!; [ForeignKey("Id")] public int CountryId { get; set; } public virtual Country Country { get; set; } = null!; [ForeignKey("Id")] public int CategoryId { get; set; } public virtual Category Category { get; set; } = null!; [Required] [StringLength(100)] public string Code { get; set; } = null!; [Required] public int CoinId { get; set; } public virtual Coin Coin { get; set; } = null!; [Required] [Column(TypeName = "money")] public decimal Amount { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] public DateTime Date { get; set; } [Required] [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] public DateTime DateEnd { get; set; } [ForeignKey("Id")] public int BuyerId { get; set; } public virtual Buyer Buyer { get; set; } = null!; [StringLength(500)] public string? Comments { get; set; } [StringLength(500)] public string? Field1 { get; set; } [StringLength(500)] public string? Field2 { get; set; } [StringLength(500)] public string? Field3 { get; set; } [StringLength(500)] public string? Field4 { get; set; } [ForeignKey("Id")] public int AuditUserId { get; set; } public virtual User AuditUser { get; set; } = null!; public DateTime AuditDateTime { get; set; } public bool AuditDelete { get; set; } }
Index视图
@model PaginatedList<WebApplicationDailyPayments.Models.Database.Order> @{ ViewData["Title"] = "Paises"; } <h1>Ordenes</h1> @if (TempData["Message"] != null) { <h6 class="text-warning">@TempData["Message"]</h6> } <p> <a class="btn btn-primary" asp-area="" asp-controller="Orders" asp-action="Create">Crear Orden</a> </p> <form asp-action="Index" method="get"> <div class="form-actions no-color"> <p> Encontrar por Nombre: <input type="text" name="SearchString" value="@ViewData["CurrentFilter"]" /> <input type="submit" value="Buscar" class="btn btn-primary" /> | <a class="btn btn-primary" asp-action="Index">Regresa a la Lista</a> </p> </div> </form> <table class="table" style="width:100%;"> <thead> <tr> <th> Proveedor </th> <th> Pais </th> <th> Categoria </th> <th> Codigo Orden </th> <th> Moneda </th> <th> Monto </th> <th> Fecha </th> <th> Fecha Tope </th> <th> Comprador </th> <th> Comentarios </th> <th> Campo 1 </th> <th> Campo 2 </th> <th> Campo 3 </th> <th> Campo 4 </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Provider.Name) </td> <td> @Html.DisplayFor(modelItem => item.Country.Acronym) </td> <td> @Html.DisplayFor(modelItem => item.Category.Name) </td> <td> @Html.DisplayFor(modelItem => item.Code) </td> <td> @Html.DisplayFor(modelItem => item.Coin.Name) </td> <td> @Html.DisplayFor(modelItem => item.Amount) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> <td> @Html.DisplayFor(modelItem => item.DateEnd) </td> <td> @Html.DisplayFor(modelItem => item.Buyer.Name) </td> <td> @Html.DisplayFor(modelItem => item.Comments) </td> <td> @Html.DisplayFor(modelItem => item.Field1) </td> <td class ='text-nowrap'> @Html.DisplayFor(modelItem => item.Field2) </td> <td class='text-nowrap'> @Html.DisplayFor(modelItem => item.Field3) </td> <td class='text-nowrap'> @Html.DisplayFor(modelItem => item.Field4) </td> <td> <a class="btn btn-warning" asp-controller="Orders" asp-action="Edit" asp-route-id="@item.Id">Editar</a> <a class="btn btn-danger" asp-controller="Orders" asp-action="Delete" asp-route-id="@item.Id">Eliminar</a> </td> </tr> } </tbody> </table> @{ var prevDisabled = !Model.HasPreviousPage ? "disabled" : ""; var nextDisabled = !Model.HasNextPage ? "disabled" : ""; } <a asp-action="Index" asp-route-sortOrder="@ViewData["CurrentSort"]" asp-route-pageNumber="@(Model.PageIndex - 1)" asp-route-currentFilter="@ViewData["CurrentFilter"]" class="btn btn-default @prevDisabled"> Previous </a> <a asp-action="Index" asp-route-sortOrder="@ViewData["CurrentSort"]" asp-route-pageNumber="@(Model.PageIndex + 1)" asp-route-currentFilter="@ViewData["CurrentFilter"]" class="btn btn-default @nextDisabled"> Next </a>
Controller Index方法
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber) { ViewData["CurrentSort"] = sortOrder; ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_asc" : ""; if (searchString != null) { pageNumber = 1; } else { searchString = currentFilter; } ViewData["CurrentFilter"] = searchString; var orders = _context.Orders.Where(u => u.AuditDelete == false).Select(all => all); if (!String.IsNullOrEmpty(searchString)) { orders = orders.Where(u => u.Code.Contains(searchString)); } switch (sortOrder) { case "name_asc": orders = orders.OrderBy(u => u.Code); break; default: break; } int pageSize = 10; return View(await PaginatedList<Order>.CreateAsync(orders.Include(o => o.AuditUser).Include(o => o.Buyer).Include(o => o.Category).Include(o => o.Coin).Include(o => o.Country).Include(o => o.Provider).AsNoTracking(), pageNumber ?? 1, pageSize)); }
内容的提问来源于stack exchange,提问作者Edgar Gomez
相关产品推荐
相关产品推荐

