I have to write a lot of code that’s going to generate Knockout JS templates from classes.
Say something like this…
<li><span>Surname</span> <span data-bind="text: SURNAME"></span></li>
which I’d like to invoke in a razor template with something like…
@className.DisplayMeFor(c=>c.SURNAME)
or even
@DisplayMeFor<className>(c=>c.SURNAME)
but I’m really stuck knowing where to start. I clearly need to do some reading up on generics but I thought it would be something like this…
public static class HtmlExtensions
{
public static MvcHtmlString DisplayMeFor<TModel, TValue>(this TModel htmlHelper, Expression<Func<TModel, TValue>> expression)
{
var s = expression.ToString(); //Clearly need a lot more code here to get name, DisplayName etc
return MvcHtmlString.Create(s);
}
}
but that’s not providing an extension to the model (i.e. @vmAppeal.DisplayMeFor(… does not compile.
Any pointers please ?
The solution I came up with was
which is called