What you need is setting up some partial views and use it when rendering the details of a car.
What is a partial view?
It's a view inside view. You can have multiple partial views in a view file.
How to use?
@Html.Partial("{your view name}", "{your model}")
So back to your example: you want to show some information related to brand and model when rendering the details of a car.
Assuming that:
- the view model for
http://localhost/brands/1 is CarBrandViewModel and
- the view model for
http://localhost/models/2 is CarModelViewModel.
Model
For your car detail page, you need to define a CarDetailViewModel:
public class CarViewModel
{
public CarBrandViewModel CarBrand { get; set; }
public CarModelViewModel CarModel { get; set; }
/* some other fields for your car */
}
And this CarViewModel will be the view model of http://localhost/car/1/2.
View
You need to define 3 view files:
- the view file for car's detail e.g.
CarDetail.cshtml;
- the partial view for brand info e.g
Shared\_CarBrandDetail.cshtml;
- the partial view for model info e.g.
Shared\_CarModelDetail.cshtml
The _CarBrandDetail.cshtml file should accepts a CarBrandViewModel object as the model:
// in your _CarBrandDetail.cshtml...
@model CarBrandViewModel
<!-- your code for rendering brand information ->
Define the similar thing in _CarModelDetail.cshtml. This time you should set:
@model CarModelViewModel
Now, in CarDetail.cshtml:
// in your CarDetail.cshtml...
@model CarViewModel
@* render your brand's details *@
@{
Html.RenderPartial("_CarBrandDetail", Model.CarBrand);
}
@* render your model's details *@
@{
Html.RenderPartial("_CarModelDetail", Model.CarModel);
}
<!-- your code for rendering other details of the car -->
Note:
A @{ } pair is required to surround the Html.RenderPartial(); call.
It's not necessary to put all the partial views under Shared folder. However, if you put the partial views somewhere else under Views, you need to change the file path when calling Html.RenderPartial().
You may want to reuse your _CarBrandDetail in http://localhost/brands/1. In this case you can make a view for the brand/{id} page and then call the _CarBrandDetail partial view.