Custom helpers setting element attributes equal to a model property

1.5k views Asked by At

Using a MVC 4.5 custom Html helper, how can I set the custom the element's id to the model's property.

I have created two classes:

public class ZClass1
{
    public ZClass2 ZClass2 { get; set; }
}

public class ZClass2
{
    public string Name { get; set; }
}

Within my View the model

@model ZClass1

I have created a simple custom Html helper:

using System;
using System.Web.Mvc;

namespace j6.SalesOrder.Web.Models.Helpers
{
    public static class SpanExtensions
    {
        public static MvcHtmlString Span(this HtmlHelper helper, string id, string text)
        {
            var tagBuilder = new TagBuilder("span");
            tagBuilder.Attributes.Add("id", id);

            return new MvcHtmlString(tagBuilder.ToString());
        }
    }
}

So, within the view the Html helper is used:

@using MyModelPath.Models.Helpers

@Html.Span("MyId","Just some text");

It renders correctly:

<span id="MyId">Just some text</span>

However, instead of hard coding the id, I would like to take advantage of using the Model, which the rendered output would be:

<span id="ZClass2.Name">Just some text</span>

Any ideas would be appreciated.

Thank you.

1

There are 1 answers

1
Raphaël Althaus On BEST ANSWER

There's a new HtmlHelper.IdFor(...) method, just use this one...

public static MvcHtmlString Span<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string text)
{
    var tagBuilder = new TagBuilder("span");
    var id = helper.IdFor(expression);
    tagBuilder.Attributes.Add("id", id.ToString());

    return new MvcHtmlString(tagBuilder.ToString());
}

usage

@Html.Span(m => m.ZClass2.Name, "Just some text")

this won't render ZClass1.ZClass2, but the usual id renderers from HtmlHelpers extension method.