Looping through view Model properties in a View

后端 未结 7 2253
南旧
南旧 2020-12-12 22:04

I have a painfully simple view model

public class TellAFriendViewModel
{
    public string Email1 { get; set; }
    public string Email2 { get; set; }
    pu         


        
相关标签:
7条回答
  • 2020-12-12 22:29

    you could use reflection over the properties, or a simple for loop to generate the same HTML as is generated in your solution, but what's your goal?
    For simplicity, what you have wins.

    Reflection

     foreach (var prop in typeof(whatever).GetProperties(BindingFlags.Instance | BindingFlags.Public))
     {
        @Html.TextBox(prop.Name, prop.GetValue(Model));
     }
    

    Loop

    var numberProperties = 5; // you could also do typeof(whatever).GetProperties(BindingFlags.Instance | BindingFlags.Public).Count();
    @for(var i = 0; i < numberProperties; i++){
     <input type="text" name="Email@i" id="Email@i"/>
    }
    
    0 讨论(0)
提交回复
热议问题