开发者

Is there a way to avoid me repeating my code in MVC Razor view?

开发者 https://www.devze.com 2023-02-26 14:22 出处:网络
I need to do something like this: <div class=\"editor-field\"> @Html.EditorFor(model => model.A1)

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)
   @Ht开发者_StackOverflowml.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.


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.


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)


You could put them in an array:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消