FloatLeft
FloatLeft

Reputation: 1337

Iteration in Razor vs ASPX

Is it possible to create a single line iteration command in my non-razor MVC view that does the following:

@Model.Toys.Each(@<input name="Make@{@(item.Index + 1)}" type="hidden" value="@item.Item.Make" />)

Upvotes: 1

Views: 768

Answers (3)

Nick Albrecht
Nick Albrecht

Reputation: 16928

You can also simply create an EditorTemplate to handle objects of type Toy (naming conventions handle this, so you could simply call it toy.cshtml if that's it's strong type) and then in your view you can simply have @Html.EditorFor(x=>x.Toys)

Upvotes: 0

Van Thoai Nguyen
Van Thoai Nguyen

Reputation: 1036

Try it: Templated Razor Delegates

http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx

His solution is exactly for your issue :D

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Even if something like this was possible I wold advice you against. It's ugly. You may take a look at templated Razor delegates instead.

Or a simple loop:

@for (var i = 0; i < Model.Toys.Length; i++) {
    <input name="Make@(i)" type="hidden" value="@Model.Toys[i].Make" />
}

or an editor template:

@Html.EditorFor(x => x.Toys)

UPDATE:

It seems that you want to rewrite this code for WebForms. So:

<% for (var i = 0; i < Model.Toys.Length; i++) { %>
    <input name="Make<%= i %>" type="hidden" value="<%= Model.Toys[i].Make %>" />
<% } %>

Upvotes: 2

Related Questions