dotnet / dotnet/aspnetcore

Allow sections to be defined inside Views and Partial Views and let them have Models

Open
#43,713 3 comments 39 reactions 0 assignees View on GitHub
area-mvc enhancement
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

If you're creating a View which itself consists of multiple partial views you can add more structure to your views.

However, splitting the view into multiple (small) files can become difficult to manage and to reason about.

### Describe the solution you'd like

I would like to use it in a way using and extending the existing concept of sections and allow them to have model parameters like Views and Partial Views already have and being able to define them in views and partial views as well.

This is what it could look like:

#### /Views/Contacts/Contact.cshtml:
```razor
@model IReadOnlyCollection

@{
ViewBag.Title = "Contacts";
Layout = "_Layout";
}

@section Details(ContactViewModel contact) {


  • @contact.Name
    @await Html.SectionAsync("ArchiveView", contact)

  • }

    @section ArchiveView(ContactViewModel contact) {


    @if (contact.IsArchived)
    {
    Unarchive
    }
    else
    {
    Archive
    }

    }

    Contacts





      @foreach (var contact in Model)
      {
      @await Html.SectionAsync("Details", contact)
      }



    ```

    From a controller perspective, I should be able to call them also, somewhat similar to partial views:

    ```csharp
    public async Task ContactDetails(Guid id) {
    var contact = await LoadContact(id);
    return Section("Contact.cshtml", "Details", new ContactViewModel(contact));
    }
    ```

    ### Additional context

    This is inspired by the idea of fragments in this [post](https://htmx.org/essays/template-fragments/).

    HTML over the wire (Hotwire, Turbo, HTMX etc.) gains more popularity and having this at hand in ASP.NET Core can make it a first class choice for those paradigms.

    Contributor guide

    Open the contributing guide

    Assessment

    This issue has not been assessed yet.

    Get new issues in your inbox

    A short digest of beginner-friendly GitHub issues.