【问题标题】:C# Where to put view specific information?C#在哪里放置查看特定信息?
【发布时间】:2011-03-07 00:33:11
【问题描述】:

我正在尝试减少我的 asp.net 网络表单中存在的代码重复。这是从数据库加载的示例对象的样子。

Apartment
  int id
  decimal rent
  bool callForPricing
  int squareFeet
  int beds
  int baths

现在我在几个不同的 asp.net 页面中从这个对象创建视图(即包含多个公寓的列表、详细视图等)。过去我所做的是创建另一个包装 Apartment 类的类。像这样的...

ApartmentView

  Apartment apt

  public virtual String Rent
  {
     get 
     { 
        if (apt.CallForPricing)
        {
           return "Call For Pricing"; 
        }else{
           return apt.Rent.ToString("C") + "/Month";
        }
     }
  }

  public virtual String BedsBathsSqFt
  {
     get 
     { 
        if (apt.squareFeet > 0)
        {
           return apt.beds + " Beds|" + apt.beds + " Beds|" + apt.SquareFeet + " sqft"; 
        }else{
           return apt.beds + " Beds|" + apt.beds + " Beds";
        }
     }
  }

如您所见,我通常只是创建数据的字符串表示形式。我考虑过让 ApartmentView 类扩展 Apartment 类,但没有因为像“Rent”这样的重叠属性。我只是想知道人们通常如何处理这种情况。这是要使用的正确命名约定吗?

【问题讨论】:

    标签: c# asp.net presenter


    【解决方案1】:

    对于任何网络表单项目来说,这是一个难以解决的难题。对于条件格式逻辑,您有两种选择 - 在页面本身中(现在您必须在整个站点上复制它),或者在您正在做的某些代码中。就关注点分离而言,两者都不是很好的选择,这是 ASP.Net 网络表单模型的一个众所周知的缺点。

    我个人会将您的视图转换为包含 FormView 控件的 .ascx Web 用户控件,并将其数据绑定到您的公寓包装对象。类似的东西:

    <asp:FormView ID="FormView1"
      DataSourceID="ObjectDataSource1"
      RunAt="server">
    
      <ItemTemplate>
        <table>
          <tr>
            <td align="right"><b>Rent:</b></td>       
            <td><%# Eval("Rent") %></td>
          </tr>
          <tr>
            <td align="right"><b>BedsBathsSqFt:</b></td>     
            <td><%# Eval("BedsBathsSqFt") %></td>
          </tr>
        </table>                 
      </ItemTemplate>                 
    </asp:FormView>
    

    让 .ascx 公开 DataSource 属性,以便可以由使用它的页面设置。

    如果数据绑定对条件表达式更灵活,您可以取消单元包装对象并将条件直接嵌入到用户控件中。但是,由于您的属性的复杂性,这可能会令人头疼。但是,您可以查看 something like this,人们试图在其中绕过这些限制。

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 2015-10-23
      • 1970-01-01
      • 2012-12-24
      • 2019-08-26
      相关资源
      最近更新 更多