Search code examples
c#asp.netasp.net-mvcrazorhtml-helper

How to do not repeat a razor code in an ASP.NET MVC "edit" view for each model property?


If you use ASP.NET MVC, then the following code must be familiar to you:

<div class="row">
    <div class="form-sm-4">
        @Html.LabelFor(m => m.att)
    </div>
    <div class="form-sm-8">
        @Html.EditorFor(m => m.att, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.att)
    </div>
</div>

This is a basic input group set with label, input and validation message.

Today I'm facing a POCO class with dozens of attributes. I mean It has N number of properties in model class. In order to build a HTML he has to repeat above code snippet N times. If there is change in DOM he has to manually change all CSS class or even certain HTML.

I am looking for a solution wherein he don't have to repeat above code snippet for dozens of model propeties.


Solution

  • Create classes:

    public static class PropertyExtensions
    {
        public static ModelWrapper<T> Wrap<T>(this T property, string propertyName)
        {
            var genericType = typeof(ModelWrapper<>);
            var specificType = genericType.MakeGenericType(typeof(T));
    
            var wrappedPropertyModel = (ModelWrapper<T>)Activator.CreateInstance(specificType);
    
            wrappedPropertyModel.ModelProperty = property;
            wrappedPropertyModel.PropertyName = propertyName;
    
            return wrappedPropertyModel;
        }
    }
    
    public class ModelWrapper<T>
    {
        public string PropertyName { get; set; }
        public T ModelProperty { get; set; }
    }
    

    Create a partial view:

    @model ModelWrapper<object>
    
    <div class="row">
        <div class="form-sm-4">
            @Html.Label(Model.PropertyName)
        </div>
        <div class="form-sm-8">
            @Html.EditorFor(m => m.ModelProperty, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(m => m.ModelProperty)
        </div>
    </div>
    

    In the main View:

    @Html.Partial("_PartialViewName", ((object)Model.YourVariableProperty).Wrap("YourVariableProperty"))