【问题标题】:How to use Html.LabelFor with dynamic expression?如何将 Html.LabelFor 与动态表达式一起使用?
【发布时间】:2012-05-14 06:01:30
【问题描述】:

我的问题很简单。

我想为对象中所有的属性值运行。例如:

public class Product
{
    public int ProductId {get;set;}
    public string Name {get;set;}
    public string Content {get;set;}
}

var obj = new Product();
var props = obj.GetType().GetProperties();

foreach(var prop in props)
{
    @Html.LabelFor( ....... ) // Need to run for active property.
    // such as @Html.LabelFor( x => prop ) 
}

我怎样才能做我想做的事?这种方式或其他方式,

【问题讨论】:

    标签: asp.net-mvc reflection lambda


    【解决方案1】:

    我没有方便的开发环境,但无论如何尝试一下

    @{ var emptyViewModel = new Product(); 
       var props = obj.GetType().GetProperties();
    
    foreach(var prop in props)
    {   
        @Html.LabelFor(model => emptyViewModel, prop.Name.ToString())  
    }
    }
    

    【讨论】:

    • 谢谢@Peter。它正在运行。
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多