Last active
May 13, 2020 21:26
-
-
Save FurkanKozen/19b0bb2aa0c3b4108ec0f58d99b6c571 to your computer and use it in GitHub Desktop.
Html helper snippet for binding properties of model dynamically
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; | |
public class Person | |
{ | |
public int ID { get; set; } | |
public string Name { get; set; } | |
public int Age { get; set; } | |
} | |
public class FakeHtmlHelper<TModel> | |
{ | |
} | |
//This is the key point | |
public static class FakeHtmlHelperExtension | |
{ | |
public static string GetName<TModel, TResult>(this FakeHtmlHelper<TModel> target, Expression<Func<TModel, TResult>> expression) | |
{ | |
var body = expression.Body as MemberExpression; | |
return body.Member.Name; | |
} | |
} | |
public class FakeViewPage<TModel> | |
{ | |
public FakeHtmlHelper<TModel> HtmlHelper { get; } | |
public FakeViewPage() | |
{ | |
HtmlHelper = new FakeHtmlHelper<TModel>(); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var view = new FakeViewPage<Person>(); | |
var propertyName = view.HtmlHelper.GetName(p => p.ID); | |
Console.WriteLine(propertyName); | |
propertyName = view.HtmlHelper.GetName(p => p.Name); | |
Console.WriteLine(propertyName); | |
propertyName = view.HtmlHelper.GetName(p => p.Age); | |
Console.WriteLine(propertyName); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With this method, instead of writing
@Html.FakeHtmlHelper("ID")
you can write@Html.FakeHtmlHelper(p => p.ID)
when using your custom Html helpers. This way, you can avoid model binding errors. This is similar to the '-for' Html helpers.