Search code examples
asp.net-mvcasp.net-mvc-3viewmodelanonymous-typespartialviews

How to use anonymous list as model in an ASP.NET MVC partial view?


I have a list of Contact objects, from which, I just want a subset of attributes. So I used LINQ projection to create an anonymous list and I passed that to a partial view. But when I use that list in partial view, compiler says that it doesn't have those attributes. I tried the simplest case as follow, but still I have no chance to use an anonymous object or list in a partial view.

var model = new { FirstName = "Saeed", LastName = "Neamati" };
return PartialView(model);

And inside partial view, I have:

<h1>Your name is @Model.FirstName @Model.LastName<h1>

But it says that @Model doesn't have FirstName and LastName properties. What's wrong here? When I use @Model, this string would render in browser:

 { Title = "Saeed" }

Solution

  • Don't do this. Don't pass anonymous objects to your views. Their properties are internal and not visible in other assemblies. Views are dynamically compiled into separate dynamic assemblies by the ASP.NET runtime. So define view models and strongly type your views. Like this:

    public class PersonViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    and then:

    var model = new PersonViewModel 
    { 
        FirstName = "Saeed", 
        LastName = "Neamati" 
    };
    return PartialView(model);
    

    and in your view:

    @model PersonViewModel
    <h1>Your name is @Model.FirstName @Model.LastName<h1>