Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid me repeating my code in 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'm using MVC3 and the razor view engine which is new to me. What I would like to do is to avoid having to repeat the same block of four lines with A1,A2,A3,A4 ... A20. Is there some way I can use a helper, template or some other feature to make it so I don't have to repeat many lines of code.

like image 547
Kenny Avatar asked Apr 19 '11 10:04

Kenny


2 Answers

One option is to use a partial view like @Ufuk mentions.

A better way IMO is to use an editor template, making use of MVC's built in conventions.

Instead of having single properties for A1, A2, etc. Put them in a 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 Shared\EditorTemplates, and MVC will do an "implicit" for each loop and render out whatever is in the editor template for the model:

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

Do not use a foreach loop - it's unnecessary and avoidable code soup.

Editor template HTML is identical to partial, strongly-typed and all. The difference is the convention to look for the file, whereas partial views need the explicit partial view name.

What this means is if you change the type of the model, it will look for that template based on the model type, allowing for a very powerful convention-based approach - which is what MVC is all about.

like image 97
RPM1984 Avatar answered Oct 14 '22 11:10

RPM1984


Create a partial view that's strongly typed to that class.

A_Partial.ascx

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

Then render them for each object.

@Html.Partial("A_Partial", model.A1)
@Html.Partial("A_Partial", model.A2)
@Html.Partial("A_Partial", model.A3)
like image 39
Ufuk Hacıoğulları Avatar answered Oct 14 '22 12:10

Ufuk Hacıoğulları