Beatles1692
Beatles1692

Reputation: 5320

How I can use a method of a model in a custom HtmlHelper

I am programming using ASP.NET MVC 3 with Razor view engine. Here's what I'd like be able to do:

@Html.DisplayWithLabel(model => model.DisplayEventDate(), "When", "")

DisplayWithLabel is a custom HTML helper that shows something with a label.

Here's its signature (or at least what I think it should look like):

public static MvcHtmlString DisplayWithLabel<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, Func<MvcHtmlString>>> expression, string label, string cssClass)

Why I am using my model like this? Well I'd like to have extensions methods for my model that will help me format its data when it's necessary (instead of formatting data inside my model itself). For example to format the event date I have this extension method:

public static MvcHtmlString DisplayEventDate(this MyEntity entity)
{
    return new MvcHtmlString(string.Format("{0}@{1}", string.Format("{0:D}", entity.EventDate),
                             string.Format("{0:t}", entity.EventDate)));
}

But when I try to browse the view I am getting an error saying that it's not possible to implicitly convert from MvcHtmlString to Func<MvcHtmlString>.

I tried to figure it out myself but I couldn't find a clue so please help me :)

Upvotes: 1

Views: 214

Answers (1)

isNaN1247
isNaN1247

Reputation: 18099

You should be able to do something like this:

public static MvcHtmlString MyMethodName<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression,
    string myText) {
    var exprValue = ModelMetadata.FromLambdaExpression(expression, 
                      htmlHelper.ViewData).Model;

    var builder = new TagBuilder("label");
    builder.SetInnerText(myText + " " + exprValue.ToString());
    return MvcHtmlString.Create(builder.ToString());

}

Upvotes: 1

Related Questions