Search code examples
c#asp.netasp.net-mvcform-helpers

ASP.NET MVC @Html.LabelFor(model => model.Name) Helper


I'm trying to create a helper that will make my form controls in the whole website

Here is what i use till now

@helper editorField(System.Linq.Expressions.Expression<Func<Model, String>> o)
{
    <div class="form-group">
        @Html.LabelFor(o, new { @class = "col-md-4 control-label" })
        @Html.ValidationMessageFor(o, "", new { @class = "col-md-6 col-xs-12  text-errer" })
        <div class="col-md-5">
            @Html.TextBoxFor(o, new { @class = "form-control" })
        </div>
    </div>
}

And the way i use it is

        @editorField(model => model.Name)
        @editorField(model => model.Email)
        @editorField(model => model.PhoneNumber)

this make it really easy to change the style and layout of the whole website in 1 place

Now here is the problem

I need to make helper for each Model and data type

Im looking for a way to make it work something like this

@helper editorField(object o)
{
        <div class="form-group">
            @Html.LabelFor(o, new { @class = "col-md-4 control-label" })
            @Html.ValidationMessageFor(o, "", new { @class = "col-md-6 col-xs-12  text-errer" })
            <div class="col-md-5">
                @Html.TextBoxFor(o, new { @class = "form-control" })
            </div>
        </div>
}

and it should work for all Models and datatypes


Solution

  • So basically what you are trying to achieve is a generic HTML helper. Unfortunately those are not supported directly in Razor views. But, you can use this workaround:

    @functions
    {
        public HelperResult PasteEditorFor<TModel, TItem>(HtmlHelper<TModel> html, Expression<Func<TModel, TItem>> expr)
        {
            return editorField(
                html.LabelFor(expr, new { @class = "col-md-4 control-label" }), 
                html.ValidationMessageFor(expr, "", new { @class = "col-md-6 col-xs-12  text-errer" }), 
                html.TextBoxFor(expr, new { @class = "form-control" }));
        }
    }
    
    @helper editorField(MvcHtmlString label, MvcHtmlString validationMessage, MvcHtmlString textBox)
    {
         <div class="form-group">
             @label
             @validationMessage
             <div class="col-md-5">
                @textBox
             </div>
         </div>
     }
    
    // usage sample
    @PasteEditorFor(Html, m => m.LongDescription)
    

    But as it is still not easy reusable (can't tell at the moment how to make it visible though all views), so I would recommend you to write usual HtmlHelper with usual static class syntax ( look at Alundra the dreamwalker comment) and add it's namespace to list of default one in WebConfig.