@Html.EditorFor(model...">

Is there a way to avoid code repetition in the MVC Razor view?

I need to do something like this:

<div class="editor-field"> @Html.EditorFor(model => model.A1) @Html.ValidationMessageFor(model => model.A1) </div> <div class="editor-field"> @Html.EditorFor(model => model.A2) @Html.ValidationMessageFor(model => model.A2) </div> <div class="editor-field"> @Html.EditorFor(model => model.A3) @Html.ValidationMessageFor(model => model.A3) </div> 

I use MVC3 and the razor viewer mechanism, which is new to me. I would like to do this so as not to repeat the same block of four lines with A1, A2, A3, A4 ... A20. Is there a way to use a helper, template, or some other function to do this, so I don't need to repeat many lines of code.

+7
source share
4 answers

One option is to use a partial view, such as @Ufuk.

It is better to use IMO to use the editor template using the MVC built into the conventions.

Instead of single properties for A1, A2, etc. Put them in IEnumerable<Something> Somethings .

Then do this in your view:

@Html.EditorFor(model => model.Somethings)

Then create an editor template called Something.cshtml and place it in the Shared\EditorTemplates , and MVC will execute “implicit” for each cycle and display everything that is in the editor template for the model:

 <div class="editor-field"> @Html.EditorForModel() @Html.ValidationMessageForModel() </div> 

Do not use the foreach loop - this is an unnecessary and invalid soup code.

The HTML editor template is identical to partial, strongly typed, and that’s all. The difference lies in the agreement to search for a file, while partial views require an explicit partial view.

This means that if you change the model type, it will search for this template based on the model type, which will allow you to use a very powerful approach based on conventions - this is what MVC is.

+11
source

Create a partial view that is strongly typed for this class.

A_Partial.ascx

 <div class="editor-field"> @Html.EditorFor(model) @Html.ValidationMessageFor(model) </div> 

Then visualize them for each object.

 @Html.Partial("A_Partial", model.A1) @Html.Partial("A_Partial", model.A2) @Html.Partial("A_Partial", model.A3) 
+6
source

You can put them in an array:

 @foreach(var item in new object[] { Model.A1, Model.A2 /* ... */ }) { <div class="editor-field"> @Html.EditorFor(item) @* ... *@ </div> } 
0
source

If possible, try putting all of them in one array / dictionary, and then use foreach.

-one
source

All Articles