如何在ASP.NET MVC“编辑"中不重复剃刀代码?查看每个模型属性? [英] How to do not repeat a razor code in an ASP.NET MVC "edit" view for each model property?

查看:72
本文介绍了如何在ASP.NET MVC“编辑"中不重复剃刀代码?查看每个模型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用ASP.NET MVC,则必须熟悉以下代码:

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.

今天,我面临着具有数十个属性的POCO课.我的意思是,它在模型类中具有N个属性.为了构建HTML,他必须重复上述代码段N次.如果DOM发生变化,他必须手动更改所有CSS类甚至某些HTML.

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.

推荐答案

创建课程:

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; }
}

创建局部视图:

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

在主视图中:

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

这篇关于如何在ASP.NET MVC“编辑"中不重复剃刀代码?查看每个模型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆