I'm starting to really enjoy working with C# and LINQ with ASP.NET. I particularly enjoy the IEnumerable extensions which are added by LINQ. I never gave LINQ much credit before. That is probably because I viewed it as a way to allow developers to get away with not knowing SQL. Now that I've had the chance to put it into action I realize that it makes .NET feel a lot like Ruby and Rails. And I like the feel of Ruby. So now I'm beginning to like the feel of C#.NET. I wish I had arrived at this point sooner. Code pr0n to follow below.
The code below is used to convert a business object into a Dictionary
suitable for use in binding to a ListControl
object. The first block is to make the ToString()
method of our business object make a string that actually means something. The next block is what converts it to be used as a DataSource for our DataBoundControl
. (ListControl
) Note: I have "broken" bracket placement conventions and nixed some type defs for brevity's sake.
// BL/Address.cs (partial class)
public partial class Address() {
public override string ToString() {
StringBuilder sb = new StringBuilder();
// code to build a 1-line address string
return sb.ToString();
}
}
// UI/Page.aspx.cs
protected void Page_Load(sender, e) {
// ...
// populate customer address drop-down
if (customerLoaded) {
// Holy LINQ extensions, Batman!
IDictionary<string, string> addressDS = null;
addressDS = cust.Addresses().ToDictionary<Address, string, string>(
addr => addr.ID.ToString(),
addr => addr.ToString()
);
CustomerAddressSelect.DataSource = addressDS;
CustomerAddressSelect.DataTextField = "Value";
CustomerAddressSelect.DataValueField = "Key";
CustomerAddressSelect.DataBind();
}
else
{ // hide the dropdown when no address is available
CustomerAddressSelect.Items.Clear();
CustomerAddressSelect.SelectedValue = String.Empty;
}
// ...
}
Keep in mind that this is all quite quick and dirty and if I were truly trying to keep things DRY I'd make this whole thing a UserControl
which I will do before the project I wrote it for is done.
Now all I need to do is start developing with ASP.NET MVC.
Comments