Search code examples
asp.net-mvc-4html-helperview-helpersrazor-declarative-helpers

Custom helpers setting element attributes equal to a model property


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.


Solution

  • 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.