I would like to create a helper that can be used like
@Html.MyHelperFor(m => m.Name)
this should return for example
<span name="Name" data-something="Name"></span>
if it is @Html.MyHelperFor(m => m.MailID)
This should return
<span name="MailID" data-something="MailID"></span>
I should be able to access the Property name in the helper method to make this type of helper ,I think.
How can I do this?
Creating HTML Helpers with Static Methods The easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. You can use the class in Listing 2 to render a <label> .
To create a custom HTML helper you have create a static class and static method. below example is for a custom HTML helper for submit button. Make sure you add below using statements. Now, You can now use it on the page where you want to define a button.
These helpers are used to render the most common types of HTML elements such as HTML text boxes, checkboxes and so on. To create a HTML form, we can use the BeginForm() and EndForm() extension methods of the HTML helper class.
Next, I describe two methods of creating custom HTML Helpers: I explain how to create custom HTML Helpers by creating a static method and by creating an extension method. An HTML Helper is just a method that returns a string. The string can represent any type of content that you want.
The HTML helper is a method that returns a string. ASP.NET MVC Framework itself contains extension methods for HtmlHelper class to have well structured helper methods separation.
When creating an HTML Helper method, you add new methods to the HtmlHelper class represented by a view's Html property. The class in Listing 3 adds an extension method to the HtmlHelper class named Label (). There are a couple of things that you should notice about this class.
By placing the CustomHelpers class inside the System.Web.Mvc.Html namespace you can then access your helper like you would the other helpers, i.e. @Html.MyHelperFor (). Show activity on this post. This should get you started.
You can do something like (the following will take additional HTML attributes too).
public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string propertyName = data.PropertyName;
TagBuilder span = new TagBuilder("span");
span.Attributes.Add("name", propertyName);
span.Attributes.Add("data-something", "something");
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
span.MergeAttributes(attributes);
}
return new MvcHtmlString(span.ToString());
}
You can use the FromLambaExpression
method from ModelMetadata
like this:
namespace System.Web.Mvc.Html
{
public static class CustomHelpers
{
public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var name = metaData.PropertyName;
// create your html string, you could defer to DisplayFor to render a span or
// use the TagBuilder class to create a span and add your attributes to it
string html = "";
return new MvcHtmlString(html);
}
}
}
The ModelMetadata
class is in the System.Web.Mvc
namespace. The FromLambdaExpression
method is what the built in helpers use so then you can be sure your helper will function the same as the built in helpers. By placing the CustomHelpers
class inside the System.Web.Mvc.Html
namespace you can then access your helper like you would the other helpers, i.e. @Html.MyHelperFor()
.
This should get you started. This function directly returns the property name but you should be able to convert this into the extension you are looking for with a little work. This example has the correct method signature and the call to ExpressionHelper to get the name of your property.
public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
string expressionName = ExpressionHelper.GetExpressionText(expression);
return new MvcHtmlString(expressionName);
}
Following up on mattytommo's answer, this works great but there is only a small problem when used with complex objects, such as if you are using this code for a property inside an EditorTemplate.
Instead of
var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string propertyName = data.PropertyName;
If using MVC4, you can change it to
var propertyName = helper.NameFor(expression);
or for MVC3 and below
var propertyName = expression.Body.ToString();
propertyName = propertyName.Substring(propertyName.IndexOf(".") + 1);
if (!string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix))
propertyName = string.Format("{0}.{1}", helper.ViewData.TemplateInfo.HtmlFieldPrefix, propertyName);
Full code:
public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
var propertyName = expression.Body.ToString();
propertyName = propertyName.Substring(propertyName.IndexOf(".") + 1);
if (!string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix))
propertyName = string.Format("{0}.{1}", helper.ViewData.TemplateInfo.HtmlFieldPrefix, propertyName);
TagBuilder span = new TagBuilder("span");
span.Attributes.Add("name", propertyName);
span.Attributes.Add("data-something", propertyName);
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
span.MergeAttributes(attributes);
}
return new MvcHtmlString(span.ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With