Sirwan Afifi
Sirwan Afifi

Reputation: 10824

Is there any way to create special controller for my _Layout?

I am developing a website that has a View called _MainPage in View\Shared folder that other views use that for basic layout of my website, so I have a section in this view that populates data from database in fact this section is latest news of the site and I should show latest news in this section ,in simple way I should make section for example called latestNews :

<ul class="news-list">
    @RenderSection("latestNews",required:false)
</ul>

and in each views I should fill this section by razor that data came from relevant controller :

@foreach (var item in Model.News)
{
    <div>
        <p>@Html.Raw(item.Body)<br /><a href="#">ادامه مطلب</a></p>
    </div>
}

in fact I have latest news in every views in footer of my pages.

now my question is : How can define a custom controller for my View (_MainPage) that haven't do these routine in each view. Is there any generic way to accomplish that?

Upvotes: 0

Views: 98

Answers (2)

Bhushan Firake
Bhushan Firake

Reputation: 9458

Any public method in a controller class is an action method. Every action method in a controller class can be invoked via an URL from web browser or a view page in application.

Your scenario is some dynamic information (data) need to displayed on couple pages in your application. Generally we end up in adding that data to model passed to views by action methods. We duplicate same data in multiple models where we brake DRY (Don’t Repeat Yourself) principle.

To handle this scenario ASP.NET MVC provides child action methods. Any action method can be child an action method but child actions are action methods invoked from within a view, you can not invoke child action method via user request (URL).

We can annotate an action method with [ChildActionOnly] attribute for creating a child action. Normally we use child action methods with partial views, but not every time.

[ChildActionOnly] represents an attribute that is used to indicate that an action method should be called only as a child action.

[ChildActionOnly]
public ActionResult GetNews(string category)
{
    var newsProvider = new NewsProvider();
    var news = newsProvider.GetNews(category);
    return View(news);
}

Above child action method can be invoked inside any view in the application using Html.RenderAction() or Html.Action() method.

@Html.Action("GetNews", "Home", new { category = "Sports"})

(or)

@{ Html.RenderAction("GetNews", "Home", new { category = "finance"}); }

Upvotes: 1

Nico Schertler
Nico Schertler

Reputation: 32597

Instead of a section, you can use Html.RenderAction to specify a controller and an action. The action should return a partial view which is then integrated within the calling site.

Upvotes: 1

Related Questions