Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" }
like image 559
Saeed Neamati Avatar asked Jul 02 '11 19:07

Saeed Neamati


People also ask

Can we use model in partial view?

Partial Views can use the Page Model for their data whereas Child Actions use independent data from the Controller. Editor/Display templates pass items from the model to the system but can be overridden by user partial views.

How do you pass model data to partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.

How does a partial view support a model?

It helps us to reduce code duplication. In other word a partial view enables us to render a view within the parent view. The partial view is instantiated with its own copy of a ViewDataDictionary object which is available with the parent view so that partial view can access the data of the parent view.

How we can call partial view in MVC?

To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.


1 Answers

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>
like image 74
Darin Dimitrov Avatar answered Oct 19 '22 21:10

Darin Dimitrov