Asp.net mvc 5 template for collecting properties

I want to group model controls with a template (preferably not hardcoded in C #). In case something changes on the layout, I can just edit the html of the template and not change it in every view.

This is what I have so far:
Views \ EditorTemplates \ InputBlock.cshtml

<section class="pure-g">
    @foreach (KeyValuePair<string, object> item in ViewData)
    {
        if (ViewData.ModelMetadata.Properties.Any(x => x.PropertyName == item.Key))
        {
            <div class="pure-u-1-2">
                @Html.Label(item.Key)
                @Html.Editor(item.Key)
                @Html.ValidationMessage(item.Key)
            </div>
        }
    }
</section>

      

And I use this pattern like this:

 @Html.EditorFor(model => model, "InputBlock", new { Model.FirstName, Model.LastName, Model.LastLogin, Model.Id })

      

This works, it renders all controls as they should be with the correct type.

The problem is that it ignores any attributes added to the model such as [Required] or [DisplayName], so the label shows the property name instead of the value specified as DisplayName, even though the properties in ModelMetadata have the correct DisplayName value.

Server side validation also works. No unobtrusive validation attributes are added when [Required] or [StringLength] is defined, only defaults are set for certain data types (like datetime or int)

How can I easily group multiple controls in a template with working attributes, preferably swapping without recompiling the project?

+3


source to share





All Articles