Should I use a repeater or a string builder to build dynamic html
I think it's obvious that the framework wants use to keep the HTML in the aspx documents, and all code in the code behind to achieve a clean level of separation.
So what do we do when the GridView
isn't good enough?
Should I:
- Use a
repeater
control to keep HTML in the presentation layer, but be forced to mix business logic in with the HTML - Or should I mix HTML in with my code behind layer in the form of a
StringBuilder
?
Let's pretend that you said use the Repeater
control.
Typically to return a product description I would do this:
<%# DataBinder.Eval(Container.DataItem, "desc") %>
But then I run into the issue of when I want to only return 150 characters of the desc in case it开发者_开发问答's too long. If my datasource was LINQ to SQL I could just create a new string:
string s = q.desc.lengh > 150 ? q.desc.SubString(0,150) + "..." : q.desc;
How would I do the same inside the repeater
within the aspx document if it is preferred I use the repeater
?
I would use a Repeater, making html in code behind is messy and hard to maintain.
No reason why you can't use helper methods in the code behind (or elsewhere) to do this
<%# SomeMethod(Eval("desc")) %>
Or on the property of the class you are repeating, have an alternative version with a getter
public class SomeItem
{
public string Desc { get; set; }
public string DescSummary
{
get
{
return Desc.Length > 150 ? string.Format("{0}...", Desc.Substring(0, 150)) : Desc;
}
}
}
And in the repeater eval DescSummary
Try
<%# Eval("desc").ToString().Length > 150 ? Eval("desc").ToString().Substring(0, 150) : Eval("desc") %>
精彩评论