目前我执行以下操作:
@{
ViewBag.Title = "Prospect";
}
<h2>@ViewBag.Prospect.Name</h2>
<table>
<tr>
<td>
<b>Address1:</b>
</td>
<td>@ViewBag.Prospect.Address1
</td>
</tr>
<tr>
<td>
<b>Postcode:</b>
</td>
<td>@ViewBag.Prospect.Postcode
</td>
</tr>
<tr>
<td>
<b>Tel:</b>
</td>
<td>@ViewBag.Prospect.Tel
</td>
</tr>
<tr>
<td>
<b>Email:</b>
</td>
<td>@ViewBag.Prospect.Email
</td>
</tr>
</table>
正如你所看到的,有很多代码,它很乱,而且,当我需要15时,我目前显示4列!
当然必须有一种更简洁的语法方法吗?使用表的替代方法?注意:所有列必须排成一行。并且还要注意,这只是希望显示1条记录。不是记录列表。
我知道在ROR中,它比这更整洁。我想我使用了formtastic或类似的显示信息。 (我不想编辑信息,只需查看它。)
答案 0 :(得分:2)
为了最大限度地减少这种情况,您可以使用反射来达到最清洁的水平。
让这成为你的ViewModel
:
public class Prospect
{
public string Name { get; set }
public string Address { get; set; }
public string PostCode { get; set; }
public string Tel { get; set; }
public string Email { get; set; }
}
这是您的Action
:
public ActionResult ViewProspect()
{
Prospect prospect = new Prospect {
Name = "Jackson",
Address = "21, Some hills",
PostCode = "90210",
Tel = "505123412",
Email = "jack@son.com"
};
Func<string, string> getStringValue = (value) => value == null ? string.Empty : value.ToString();
IEnumerable<KeyValuePair<string, string>> prospectKeyValue = typeof(Prospect).GetProperties().Select(
p => new KeyValuePair<string, string>(p.Name, getStringValue(p.GetValue(prospect, null))));
ViewBag.Prospect = prospectKeyValue;
View();
}
这是您简化的View
:
@{
ViewBag.Title = "Prospect";
}
<h2>@ViewBag.Prospect.Single(p => p.Key == "Name").Value</h2>
<table>
@foreach(var keyValue in ViewBag.Prospect)
{
<tr>
<td>
<b>@keyValue.Key</b>
</td>
<td>@keyValue.Value
</td>
</tr>
}
</table>