LINQ Anonymous Types + MVC Views

后端 未结 6 1561
心在旅途
心在旅途 2021-01-03 00:40

I\'ve seen many questions about this, but i\'ve never really got the answer that I need.

I\'m converting a fairly large web application from Web Forms to MVC and af

6条回答
  •  忘掉有多难
    2021-01-03 01:14

    If you want to avoid creating a separate class just for displaying your one projection, you could also resort to using a dictionary, like so:

    from person in personList select new Dictionary
    { 
        { "Name", person.Firstname + " " + person.Lastname },
        { "Id", person.Id.ToString() }
    };
    

    You can then type your viewpage to

    ViewPage>>
    

    And finally iterate over the list in the view like so:

    <% foreach (Dictionary p in (IEnumerable)ViewData.Model) 
    { %>
       
  • <%=p["Id"] %> - <%= p["Name"] %>
  • <% } %>

    Needless to say, the drawback is that your code is now rather full of "magic strings", making it more error prone because of the absence of compile time checking.

提交回复
热议问题