ASP.NET mvc html 列显示
Posted
技术标签:
【中文标题】ASP.NET mvc html 列显示【英文标题】:ASP.NET mvc html columns displaying 【发布时间】:2016-08-05 02:15:21 【问题描述】:我想建立两列,第一列应包含FirstList
的项目,第二列应包含SecondList
的项目。为什么在我的实现中将一列放在另一列之下?如何解决这个问题?我需要使用 css 样式而不是 html?
控制器和类:
namespace MvcApplication4.Controllers
public class HomeController : Controller
//
// GET: /Home/
public ActionResult Index()
List<Employee> emp1 = new List<Employee>();
emp1.Add(new Employee Number="1",Text="dfsfdsfsafdsafdasfadsf");
emp1.Add(new Employee Number = "2", Text = "asdfsa" );
emp1.Add(new Employee Number = "3", Text = "dfsfdsfdasfsafdsafdasfdsafsaadsf" );
List<Employee> emp2 = new List<Employee>();
emp2.Add(new Employee Number = "1", Text = "dfsfdsfsafdsafdasfadsf" );
emp2.Add(new Employee Number = "2", Text = "asdfsa" );
emp2.Add(new Employee Number = "3", Text = "dfsfdsfdasfsafdsafdasfdsafsaadsf" );
emp2.Add(new Employee Number = "4", Text = "asdfsa" );
emp2.Add(new Employee Number = "5", Text = "dfsfdsfdasfsafdsafdasfdsafsaadsf" );
return View(new IndexViewModel FirstList = emp1, SecondList = emp2 );
public class IndexViewModel
public IEnumerable<Employee> FirstList get; set;
public IEnumerable<Employee> SecondList get; set;
public class Employee
public string Text get; set;
public string Number get; set;
索引.cshtml
@model MvcApplication4.Controllers.IndexViewModel
@
ViewBag.Title = "Index";
<h2>Index</h2>
<table>
<tbody>
@foreach (var item in Model.FirstList)
<tr>
<td>@item.Number</td>
<td>@item.Text</td>
</tr>
@foreach (var item in Model.SecondList)
<tr>
<td>@item.Number</td>
<td>@item.Text</td>
</tr>
</tbody>
</table>
【问题讨论】:
【参考方案1】:您将两个模型的值直接写到同一个表中。为了实现我认为您正在尝试做的事情,您需要将值分隔到单独的表中,并使用 HTML 和 CSS 相应地定位它们。
@model MvcApplication4.Controllers.IndexViewModel
@
ViewBag.Title = "Index";
<h2>Index</h2>
<table>
<tbody>
@foreach (var item in Model.FirstList)
<tr>
<td>@item.Number</td>
<td>@item.Text</td>
</tr>
</tbody>
</table>
<table>
<tbody>
@foreach (var item in Model.SecondList)
<tr>
<td>@item.Number</td>
<td>@item.Text</td>
</tr>
</tbody>
</table>
【讨论】:
【参考方案2】:此代码按您的预期工作:
<table border="1">
<thead>
<th colspan="2">First List</th>
<th colspan="2">Second List</th>
</thead>
<tbody>
@for (int i = 0; i < Math.Max(Model.FirstList.Count(), Model.SecondList.Count()); i++)
Employee first = Model.FirstList.Count() > i ? Model.FirstList.ToList()[i] : null;
Employee second = Model.SecondList.Count() > i ? Model.SecondList.ToList()[i] : null;
<tr>
<td>@(first?.Number)</td>
<td>@(first?.Text)</td>
<td>@(second?.Number)</td>
<td>@(second?.Text)</td>
</tr>
</tbody>
</table>
您应该合并两个 foreach 循环以并排显示列表。
【讨论】:
以上是关于ASP.NET mvc html 列显示的主要内容,如果未能解决你的问题,请参考以下文章
是否可以在 ASP.NET MVC 的脚本块中引用 ViewData?
ASP.Net MVC - Razor 按月/年列显示客户的帐户总数