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)
}
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.
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>
}
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)))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With