Created
March 2, 2010 15:17
-
-
Save actaneon/319571 to your computer and use it in GitHub Desktop.
Sample implementation of TextBoxFor using an expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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