Simplest Way To Do Dynamic View Models in ASP.NET MVC 3

后端 未结 2 2004
北荒
北荒 2020-12-10 22:32

Caveat: This might be an inappropriate use of C#\'s dynamic keyword and I probably should be using a strongly-typed view model, but...

I\'m trying t

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 23:04

    Ok, you could do the following, but I wouldn't recommend it. Create a static method similar to the following

    public static IHtmlString DisplayProperty(object obj, string property) {
        return new HtmlString(TypeDescriptor.GetProperties(obj)[property].GetValue(obj).ToString());
    }
    

    Then in your cshtml file make the following call (make sure to using your proper namespace)

    
        @foreach (var item in Model) {
        
            @DisplayProperty(x, "RateCodeName")
            @DisplayProperty(x, "Year")                            
            @DisplayProperty(x, "Rate")
            >@DisplayProperty(x, "Comment")
        
        }
    
    

    I wouldn't recommend this though but it is a solution to your problem that doesn't require a model.

提交回复
热议问题