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

后端 未结 2 2002
北荒
北荒 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:00

    Like you said, it's not supported. (I'm not saying dynamic View Models aren't supported - I'm saying what you're trying to do is not)

    You could probably neaten up the LINQ query, but in the end your best bet would be to simply create a custom View Model. Seriously, it will take you about 30 seconds to do that.

    I know dynamic is new and cool and everything, but your code will be a lot neater and easier to maintain if you just stick with a custom View Model in this case.

    I would only go with a dynamic View Model in the very simple scenarios - most of the time you probably want to stick with what we've been doing all along - custom View Models.

    0 讨论(0)
  • 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)

    <tbody>
        @foreach (var item in Model) {
        <tr>
            <td>@DisplayProperty(x, "RateCodeName")</td>
            <td>@DisplayProperty(x, "Year")</td>                            
            <td>@DisplayProperty(x, "Rate")</td>
            <td>>@DisplayProperty(x, "Comment")</td>
        </tr>
        }
    </tbody>
    

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

    0 讨论(0)
提交回复
热议问题