简体   繁体   中英

MVC pattern : best way to display an array of elements

Suppose I have this div on the view section :

<div class='my class'>
    <%=myVariableToPrint %>
</div>

There isnt problems there : I just take from my class/bean ( model ) my data and put it on a div.

Now, suppose that myVariableToPrint is an array of 10 strings, and I need to print the div 10 times, each div for each string on the array. How can I do it?

Put the div on the model like :

myString+="<div class='my class'>"+myVariable[i]+"</div>" 

and print myString on the view section it's noisy :)

Any solutions?

Ps I'm speaking about C# there, but should be the same on Java ecc

Just put the <div> inside the loop

<% foreach (var item in myArray) { %>
    <div class='my class'>
        <%= item %>
    </div>
<% } %> 

Update Ok, from your comments it looks like you don't want any loop logic in your views. Really you shouldn't worry about that. Views have that kind of stuff in. It might look a bit messy but it is generally the correct way to do things. Putting html in your model just so that you can render it is definitely a really bad idea . Please don't do that.

One other way you could do it would be with a custom Html.Helper method.You could do something like....

public static string DivList(this HtmlHelper helper, IList<string> list, string divClass)
{
    var sb = new StringBuilder();
    foreach(string item in list)
    {
        sb.AppendFormat("<div class=\"{0}\">{1}</div>", divClass, item); 
    }     
    return sb.ToString();
}

And you can use this in the view like...

<%= Html.DivList(Model.MyList, "myClass") %>

which is a lot neater.

You should iterate the collection using a foreach loop and put your HTML inside the loop.

Using Razor (because it's easier):

@foreach(string s in something {
    <div class="Something">@s</div>
}

Put the collection in the model.

The view iterates over the collection to create the final output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM