Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom Html Helper: MyHelperFor

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?

like image 790
Kuttan Sujith Avatar asked Aug 27 '13 17:08

Kuttan Sujith


People also ask

Can we create custom HTML helper?

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

How can create custom HTML helper in asp net core?

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.

Which option is a built in HTML helper?

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.

How do I create custom HTML helpers?

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.

What is htmlhelper in ASP NET?

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.

How do I add an extension method to the htmlhelper?

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.

How do I add a custom helper class to a MVC application?

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.


4 Answers

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());
}
like image 116
mattytommo Avatar answered Oct 24 '22 10:10

mattytommo


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().

like image 38
asymptoticFault Avatar answered Oct 24 '22 08:10

asymptoticFault


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);
    }
like image 2
Grax32 Avatar answered Oct 24 '22 09:10

Grax32


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());
    }
like image 1
jBelanger Avatar answered Oct 24 '22 09:10

jBelanger