Ash
Ash

Reputation: 3532

ASP.NET MVC Model Data - Loop

I've got a strongly typed View which displays data from my model (which comes from a database table), such as:

Model.servicetype Model.serviceid

All the fields within this model contain true or false values.

I simply wanted to loop through the Model and either replace the values of true and false, or create some sort of generic list and output the data from that. enter image description here

Note this is only for display purposes, the user can't edit etc.

Hope that makes sense.

Thanks

Upvotes: 1

Views: 444

Answers (2)

balexandre
balexandre

Reputation: 75073

So ... just create a static extension method and called for example ToWord in your Utilities class as

public static string ToWord(this bool value)
{
    return value ? "Yes" : "No";
}

and then use:

<%= Html.Encode(Model.breakpads.ToWord()) %>

P.S. With all the simple Razor Views ... why are you using WebForm Views? Rzor is so much simpler! :)

Upvotes: 2

smartcaveman
smartcaveman

Reputation: 42246

<%= string.Join(string.Empty,
    ViewData
    .ModelMetadata
    .Properties
    .Where(x => x.ModelType == typeof(bool))
    .Select(x => new { 
                           Name = x.GetDisplayName(), 
                           Value = (bool)x.Model
                     })
    .Select(x => string.Format(@"
<tr>
    <td>{0}</td>
    <td>{1}</td>
</tr>",
        x.Name,
        Html.Encode(x.Value ? "Yes" : "No"))
        .ToArray()))                            
%>

Note that the call to ToArray() is unnecessary in .NET 4.0

Upvotes: 0

Related Questions