开发者

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?

P.s. 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜