2012-11-30 23 views
2

我正在使用mvc 4 web应用程序。我是一个新手(刚刚在几天前开始,所以请对我好)。将mvc存储​​库提取的数据定位到视图中(MVC4 Web)

所以我设法从一个Repository类获取数据到一个视图。这里没问题。但问题是,我想要这样做,以便这些数据以水平方式显示在两列中,每列有两个块。到目前为止,数据正在垂直布局,从上到下。

<div id="myID"> 
    @foreach(var stuff in Model) 
    { 
     <article>@stuff.title</article> 
    } 
</div> 

上面的代码是我正在进行的简化版本。但同样,数据显示,就像列表中,从上到下显示,我要显示这样的数据:

A B 
C D 

任何帮助将是非常赞赏。

谢谢

+1

这里的关键字是'我想**显示**水平'。意味着它与你的HTML和CSS有关。尝试使用'

'来安排你的显示。 – JofryHS

+0

感谢@JofryHS的输入。你是对的。它必须是HTML和CSS。 – ito

回答

2

您可以实现您的目标(不使用讨厌的表)的一种方法是使用CSS来布局您的文章。

一个更简单的探讨这样HTML相关问题的方法是创建一个只包含你正在寻找的元素的简单的HTML页面:

<!DOCTYPE html> 

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta charset="utf-8" /> 
    <title></title> 
    <style> 
     div#articles { 
      width: 450px; 
      border: solid 1px red; /* For debugging purposes */ 
     } 

     div#articles article{ 
      display: inline-block;  /* Force the article to be displayed in a rectangular region laid out next to one another */ 
      margin: 5px;    /* Leave a little room between each article */ 
      width: 200px;    /* Limit the maximum width of the article so that only two fit side-by-side within the div */ 
      text-align: center;   /* Center the text horizontally */ 
      vertical-align: middle;  /* Center the text vertically */ 
      border: solid 1px green; /* For debugging purposes - so you can see the region the articles live within */ 
     } 
    </style> 
</head> 
<body> 
    <div id="articles"> 
     <article>Article A</article> 
     <article>Article B</article> 
     <article>Article C</article> 
     <article>Article D</article> 
    </div> 
</body> 
</html> 

条,款等的正常布局的流动元素大小为包含它们的元素的宽度(在您的示例中为DIV)。

您希望您的文章以网格状模式布局,因此您需要告诉浏览器将这些特定元素渲染为“块”。此外,您希望在其父项内流动的块,使得只有两个块可以并排放入包含的DIV中。

因此,使用CSS样式,您可以:1. 设置你的DIV的宽度为固定大小 2.设置你的文章被渲染为“inline-block的”风格 3.设置你的文章宽度,只有两个可适用于每一行 可选: 4.如有必要,将文章的文本置于中心 5.设置文章的边距,在每个文章之间留出一点空间 6.为了更好地查看每个元素所在的区域,请使用简单1px彩色边框

此方法产生以下布局: enter image description here

HTH。

+0

哇!非常感谢你。我今晚将实施这个报告并回报。这是非常详细的。那真是太好了。谢谢。 – ito

+0

你好@Richard Turner!为您的实施!它像魔术一样工作。如果你不介意,我还有另一个与'Json'有关的快速问题。实质上,我想用来自'Repository'Model-class中定义的函数的数据填充这些文章。我需要使用'Ajax'。 – ito

0

按照我的意见,你可能想是这样的,用<table>来安排你的输出。

<div id="myID"> 
    @{ 
     int count = 0; 
     <table> 
     @foreach(var stuff in Model) 
     { 
     if (count % 2 == 0){ <tr> }  
      <td> 
       <article>@stuff.title</article> 
      </td> 
     @if (count % 2 == 1) { </tr> } 
     count++; 
     } 
     </table> 
    } 
</div> 

还没有测试过,但大概这会做或给你的想法。 :)