Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the shared layout view have a controller in ASP.NET MVC?

Tags:

Can the shared layout view have a controller?

I need to pass it Model information from a Controller?

Or am I missing something here?

like image 246
Pinch Avatar asked Sep 16 '13 15:09

Pinch


People also ask

Can two different controllers access a single view in MVC?

Yes. Mention the view full path in the View method. If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter. The View name should be same as the Action method name.

Can partial view have controller?

It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.

Can we have multiple _ViewStart in MVC?

We can also create multiple _ViewStart. cshtml pages. The file execution is dependent upon the location of the file within the folder hierarchy and the view being rendered. The MVC Runtime will first execute the code of the _ViewStart.

What is shared view in MVC?

If a view isn't found in this location, then by convention the MVC runtime looks in the “Views\Shared”. This simple organization scheme works well for small projects, but can become quite unwieldy as the size of the web site grows and the shared folder becomes an ever larger dumping ground.


2 Answers

In the controller:

    public PartialViewResult Menu()
    {
        var ChargeTypes = db.ChargeTypes.ToList();
        return PartialView(ChargeTypes);
    }

And then its partial view:

@model IEnumerable<ProposalMaker.Models.ChargeType>

@foreach (var item in Model)
{
    <li>@item.Name</li>
}

Then in the shared partial view

@{Html.RenderAction("Menu","ChargeType");}

Thanks for the tip SLaks!

like image 162
Pinch Avatar answered Sep 17 '22 16:09

Pinch


To pass information to the layout, you will need to use a base view model that is used by all your view models. Your layout can then take this base model.

I have previously answered an SO question on this

Pass data to layout that are common to all pages

Which has a detailed example.

like image 42
Colin Bacon Avatar answered Sep 19 '22 16:09

Colin Bacon