Let the aspx page autonomously control the number and type of call records which can be changed at any time without recompiling the implementation method

  • 2020-05-12 02:30:37
  • OfStack

However, for small sites, we can easily find some of the powerful features of.net to make it easier for us to use.
We know that a page will often call a lot of data, there are lists, there are single, especially lists, we often write different methods for different lists in.cs file,11 using "list.DataSource = data source; List. DataBind (); To complete the binding, which makes our cs page swell!! I often feel the urge to start all over again, but over and over again, I write 1 pile of trash. Well, this time I decided to write just one method, less than 15 lines long enough for the entire page to be called.

The common sense we need to use is "late binding "," run CS first, then aspx", which I believe you all have.
Step 1: first define a protected method in cs:
 
/// <summary> 
///  Get a list of news data  
/// </summary> 
/// <param name="num"> The number of requests </param> 
/// <param name="cateId"> category ID</param> 
/// <param name="isTop"> Is placed at the top </param> 
/// <param name="isCommend"> Whether to recommend </param> 
/// <returns>1 A news data set ,News Is the news , Of course, ,List<XXXX> The name depends on your data source </returns> 
protected List<News> GetNewsData(int num,int cateId,int isTop,int isCommend){ 
if (num < 0) num = 0; 
List<News> result = new List<News>(); 
Expression<Func<News, bool>> expr = PredicateExtensionses.True<News>(); 
if (isPic) { 
expr = expr.And(c => c.IsPic == 1); 
} 
if (cateId > 0) { 
expr = expr.And(c => c.cateId == cateId); 
} 
if (isTop > -1) { 
expr = expr.And(c => c.IsTop == isTop); 
} 
if (isCommend > -1) { 
expr = expr.And(c => c.IsCommend == isCommend); 
} 
return nm.AllNews.Where(expr).OrderByDescending(c=>c.ID).Take(num).ToList(); 
} 

Step 2: in the Page_Load method, call DataBind();
 
protected void Page_Load(object sender, EventArgs e) 
{ 
DataBind(); 
} 

All of the above is my method to say here is under 1 call business logic in a public class, creates an expression tree class - this class here (/ / www. ofstack. com article / 28043. htm), and general business logic class;
Step 3, next is our aspx call. Here I use the simplest Repeater to illustrate!
 
<asp:Repeater ID="Repeater6" runat="server" DataSource='<%#GetNewsData(10,3548,-1,-1)%>'> 
<ItemTemplate> 
<%#Eval("Subject")%> 
</ItemTemplate> 
</asp:Repeater> 

Ok, all work is done. If you want to call another category, or if you want to change the number, just change it on the page.cs and build!
Isn't that convenient?
For the explanation of DataBind(), why write DataBind() in Page_load, which is to give data to the data source in advance! Otherwise, because of the late binding relationship, will make the data control can not find the data source and error!

Related articles: