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" }
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With