Skip to content

Instantly share code, notes, and snippets.

@FurkanKozen
Last active May 13, 2020 21:26
Show Gist options
  • Save FurkanKozen/19b0bb2aa0c3b4108ec0f58d99b6c571 to your computer and use it in GitHub Desktop.
Save FurkanKozen/19b0bb2aa0c3b4108ec0f58d99b6c571 to your computer and use it in GitHub Desktop.
Html helper snippet for binding properties of model dynamically
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();
}
}
@FurkanKozen
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment