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

孤街浪徒 提交于 2021-01-28 10:11:36

问题


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.


回答1:


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"))


来源:https://stackoverflow.com/questions/44962569/how-to-do-not-repeat-a-razor-code-in-an-asp-net-mvc-edit-view-for-each-model-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!