2012-03-21 66 views
22

如何从if()@foreach()中将html添加到页面中。我得到没有得到任何具体的错误,它只是不采取第二if()。它像文字一样写出来。如何将html添加到Razor if语句中的页面中?

这是我试过,但没有运气

@foreach (var item in Model) 
    { 
     if (count % 4 == 0 || totaltCount == 1) 
     { 
     <div class="in-instructor-container"> 
      } 
      <div class="in-instructor"> 
       <h3>@item.Name</h3> 
       @item.Information 
      </div> 
     if ((count - 1) % 3 == 0 || count == totaltCount) { 
     </div> 
     } 

     count++; 
    } 

我的html得到这样

 <div class="in-instructor-container"> 
      } 
      <div class="in-instructor"> 

       <h3>Test Person 0</h3> 
       bla bla bla bla bla bla bla 
      </div> 
     if ((count - 1) % 3 == 0 || count == totaltCount) { 
     </div> 
+0

-1为什么?请激励 – 2012-03-21 18:53:20

+0

我不是那个推倒你的人,但没有更多的信息你不会得到任何帮助。有错误吗?这个问题是什么? – 2012-03-21 18:54:18

回答

45

您需要添加@:在html前面的if语句里面:

@foreach (var item in Model) 
{ 
    if (count % 4 == 0 || totaltCount == 1) 
    { 
     @:<div class="in-instructor-container"> 
    } 
     <div class="in-instructor"> 
      <h3>@item.Name</h3> 
      @item.Information 
     </div> 

    if ((count - 1) % 3 == 0 || count == totaltCount) { 
     @:</div> 
    } 

    count++; 
} 

我发现这个解决方案从this stackoverflow question

+0

非常感谢,我还没有做太多mvc 3。 – 2012-03-21 19:10:54

+0

@ Dejan.S您的欢迎!我也学到了一些新东西;)。 – 2012-03-21 19:11:34

+0

如果可以的话,我会赞成这一百万次,因为在这个问题上stackoverflow有太多的答案 – pat8719 2013-06-14 22:41:43