Skip to content

Instantly share code, notes, and snippets.

@actaneon
Created March 2, 2010 15:17
Show Gist options
  • Save actaneon/319571 to your computer and use it in GitHub Desktop.
Save actaneon/319571 to your computer and use it in GitHub Desktop.
Sample implementation of TextBoxFor using an expression
using System;
using System.Linq.Expressions;
using System.Text;
namespace CSTest.TextBoxExpression
{
public class TextBoxTest
{
public void Test()
{
var service = new TextboxService();
var item = new Item { Name = "Snowboard", HitCount = 5, IsActive = true };
var tb1 = service.TextBoxFor(item, i => i.Name);
Console.WriteLine(tb1);
}
}
public class Item
{
public string Name { get; set; }
public int HitCount { get; set; }
public bool IsActive { get; set; }
}
public class TextboxService
{
public string TextBoxFor<T>(T item, Expression<Func<T, object>> expression)
{
var sb = new StringBuilder();
sb.Append("<input type='text' ");
// get some meta data from the expression
var mexpression = expression.Body as MemberExpression;
var name = string.Format("{0}{1}", mexpression.Member.DeclaringType.Name, mexpression.Member.Name);
sb.AppendFormat("name='{0}' ", name);
// compile the expression and use it to get the value
var function = expression.Compile();
var value = function(item);
sb.AppendFormat("value='{0}' ", value);
sb.Append("/>");
// <input type='text' name='ItemName' value='Snowboard' />
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment