Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through view Model properties in a View

I have a painfully simple view model

public class TellAFriendViewModel
{
    public string Email1 { get; set; }
    public string Email2 { get; set; }
    public string Email3 { get; set; }
    public string Email4 { get; set; }
    public string Email5 { get; set; }
}

And then the corresponding inputs on my view, but I'm wondering if there is a better way (such as a loop) to write similar TextBoxes to my view:

@using (Html.BeginForm()){
    @Html.AntiForgeryToken()

    @Html.TextBoxFor(vm => vm.Email1)
    @Html.TextBoxFor(vm => vm.Email2)
    @Html.TextBoxFor(vm => vm.Email3)
    @Html.TextBoxFor(vm => vm.Email4)
    @Html.TextBoxFor(vm => vm.Email5)
}
like image 317
Nick Brown Avatar asked Mar 28 '12 22:03

Nick Brown


People also ask

What is foreach loop in MVC?

Generally, the loops in asp.net mvc razor view will work same as other programming languages. We can define the loop inside or outside the code block in razor, and we can use the same foreach looping concept to assign value to define the condition.


2 Answers

You should access

ViewData.ModelMetadata.Properties. No reason to double the reflection effort, plus it figures out DataAttributes metadata for you.

@foreach(var property in ViewData.ModelMetadata.Properties)
{
    <div class="editor-line">
        <label>@(property.DisplayName??property.PropertyName)</label>
        @Html.Editor(property.PropertyName)
    </div>
}
like image 96
moribvndvs Avatar answered Oct 27 '22 17:10

moribvndvs


You should consider using an array.

However, if you wanted to go with reflection, it would look like this:

@foreach (var prop in Model.GetType().GetProperties())
{
    @(Html.TextBox(prop.Name, prop.GetValue(Model, null)))
}
like image 36
Xavier Poinas Avatar answered Oct 27 '22 19:10

Xavier Poinas