通过视图模型的属性在视图中循环 [英] Looping through view Model properties in a View

查看:120
本文介绍了通过视图模型的属性在视图中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个痛苦的简单视图模型

 公共类TellAFriendViewModel
{
    公共字符串Email1 {获得;组; }
    公共字符串Email2 {获得;组; }
    公共字符串Email3 {获得;组; }
    公共字符串Email4 {获得;组; }
    公共字符串Email5 {获得;组; }
}
 

然后在我的观点相应的投入,但我不知道是否有更好的方法(如循环)来编写类似的文本框,以我的观点:

  @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)
}
 

解决方案

您应该访问

ViewData.ModelMetadata.Properties 。没有理由加倍反射努力,再加上它的数字数据属性的元数据给你。

  @foreach(在ViewData.ModelMetadata.Properties VAR属性)
{
    < D​​IV CLASS =总编辑在线>
        <标签> @(property.DisplayName ?? property.PropertyName)< /标签>
        @ Html.Editor(property.PropertyName)
    < / DIV>
}
 

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)
}

解决方案

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>
}

这篇关于通过视图模型的属性在视图中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆