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.
There's a new HtmlHelper.IdFor(...) method, just use this one...
usage
this won't render ZClass1.ZClass2, but the usual id renderers from HtmlHelpers extension method.