C # Where to specify specific information?

I am trying to reduce code duplication that exists in all my asp.net web forms. Here's what an example of an object loaded from a database looks like.

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

Now I create views from this object on several asp.net pages (i.e. a list with several apartments, a detailed view, etc.). In the past, what I did was create another class that wraps the Apartment class. Something like that...

 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"; } } } 

As you can see, I usually create string representations of the data. I considered asking the ApartmentView class to extend the Apartment class, but not because of matching properties like Rent. I'm just wondering how people usually deal with this situation. Is this the correct naming convention?

+4
source share
1 answer

This is a difficult dilemma for working on any webforms project. You have two options for the conditional formatting logic - on the page itself (now you should duplicate it throughout the site) or in some code, as you do. There are also no great options in terms of sharing problems; this is a well-known drawback of the ASP.Net web form model.

Personally, I would turn your view into a custom .ascx control that contains the FormView control and binds it to the apartment wrapper. Sort of:

 <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> 

Have a .ascx, set the DataSource property so that it can be set on the page using it.

If the Databinding was more flexible with conditional expressions, you could remove the apartment wrapper object and paste the conditions directly into the user control. Despite the complexity of your properties, this is likely to be a big headache. However, you can see something like this where people tried to get around these restrictions.

+2
source

Source: https://habr.com/ru/post/1313561/


All Articles