2016-06-15 96 views
1

我正在开发一个使用C#和MVC的Web应用程序。其中一个页面有多个<tr>,其中将包含信息,但该信息会随着时间(1个月至6个月)范围而更新。所以我只想显示包含信息的<tr>。信息存储在数据库中,每个<tr>都有自己的专栏。我所采用的方法是读取数据并在视图中应用if条件。根据条件显示表格行

因此,像

@if (!string.IsNullOrEmpty(Model.SomePropertyOne)) 
{ 
    <tr> 
    <td>@Html.DisplayNameFor(model => model.SomePropertyOne)</td> 
    <td>@Html.DisplayFor(model => model.SomePropertyOne)</td> 
    </tr> 
} 
@if (!string.IsNullOrEmpty(Model.SomePropertyTwo)) 
{ 
    <tr> 
    <td>@Html.DisplayNameFor(model => model.SomePropertyTwo)</td> 
    <td>@Html.DisplayFor(model => model.SomePropertyTwo)</td> 
    </tr> 
} 
... 

我有这个8倍。所以我的问题是,有没有比这更好的方法,或者我坚持使用所有这些if陈述?

请让我知道如果你需要任何进一步的信息

+0

在你的榜样,是两行应该涉及到不同的属性?因为他们都参考'model.SomeProperty' – stuartd

+0

@stuartd是的,他们都涉及到不同的属性 – Code

+0

可能重复http://stackoverflow.com/questions/16814119/how-do-i-conditionally-show-a-field- in-asp-net-mvc-razor –

回答

1

您可以创建一个DisplayTemplate包含该条件。在/Views/Shared/DisplayTemplates/创建的局部视图(比方说)MyTemplate.cshtml

@model string 
@if (!string.IsNullOrEmpty(Model)) 
{ 
    <tr> 
     <td>@Html.DisplayNameFor(m => m)</td> 
     <td>@Model</td> 
    </tr> 
} 

然后在视图

@Html.DisplayFor(m => m.SomeProperty, "MyTemplate") 
@Html.DisplayFor(m => m.AnotherProperty, "MyTemplate") 
.... //etc 

DisplayFor()基于模板将生成的HTML,因此,如果该属性的值是nullstring.Empty,那么该属性将不会生成任何内容。

备注:您不应该使用<table>元素进行布局(请参阅Why not use tables for layout in HTML?Why Tables Are Bad (For Layout*) Compared to Semantic HTML + CSS)。相反,使用CSS来设计你的布局。例如,改变DisplayTemplate

<div class="field"> 
    <div class="field-label">@Html.DisplayNameFor(m => m)</div> 
    <div class="field-value">@Model</div> 
</div> 

,并添加以下CSS

.field { 
    position: relative; 
    margin: 5px 0; 
} 
.field-label { 
    position: absolute; 
    width: 240px; 
    color: #808080; 
} 
.field-value { 
    margin-left: 250px; 
} 
0

可以解决通过反射你的问题,这样的事情:

@foreach(var prop in Model.GetType().GetProperties().Where(x => x.PropertyType == typeof(string))) 
{ 
    var value = prop.GetValue(Model); 
    if (value != null) 
    { 
     <tr> 
      <td>@prop.Name</td> 
      <td><input value="@value.ToString()" name="@prop.Name" /></td> 
     </tr> 
    } 
} 

但是,在这种情况下,你应该避免使用@Html帮手,而是 - 明确写入相应的html。