【问题标题】:Neater way to display custom class in ASP.net webpage?在 ASP.net 网页中显示自定义类的更简洁的方式?
【发布时间】:2018-01-21 00:42:59
【问题描述】:

目前我执行以下操作:

@{
    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 或类似的东西来显示信息。 (我不想编辑信息,只是查看它。)

【问题讨论】:

    标签: asp.net html-table


    【解决方案1】:

    为了尽量减少这种情况,您可以使用反射以达到最干净的水平。

    让这成为你的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>
    

    【讨论】:

    • 非常详细的答案。谢谢十亿。现在试试看。
    • 在整数字段的情况下提供问题。他们似乎没有显示
    • 只需将p.GetValue(prospect, null) as string更改为p.GetValue(prospect, null).ToString()即可。
    • 那前景中的值为空的情况呢?谢谢
    • 我选择了(p.Name, (p.GetValue(prospect, null) ?? "").ToString()) 来保存额外的功能。不过谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 2014-10-30
    • 2016-11-30
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多