asp.net-corelayoutpartial-views

How to pass parameters from specific view to _Layout.cshtml?


I have a tool site, and the site layout was arranged like below. Black square has the main content, and when you go to a specific tool now I want to display the related tools on the right side.

enter image description here

Now to avoid Col-md duplication on every page I arranged the Layout page like this

  <div class="container">
        <div class="row">
            <div class="col-md-7">
                <main role="main" class="pb-3">
                    @RenderBody()
                </main>
            </div>
            <div class="col-md-5">
                //Related tools widget
            </div>
        </div>

So inside above code the I want to display this related tools widget. But there is a condition. When you go to a specific tool, that specific tool should not be displayed in that widget. So I created a partial view, and now I don't know where to call it.

How to achieve that? Is my structure all right? Instead of using col-md on the layout shall I use them on a specific view like the one below?

  <div class="row">
            <div class="col-md-7">
               //Content goes here
            </div>
            <div class="col-md-5">
               @RenderSection("RelatedTools", required:true)
            </div>
        </div>

Solution

  • Since you have using @RenderSection("RelatedTools", required:true),you need to add @section RelatedTools {} in your each view:

    Layout:

    <div class="container">
            <div class="row">
                <div class="col-md-7">
                    <main role="main" class="pb-3">
                        @RenderBody()
                    </main>
                </div>
                <div class="col-md-5">
                    @RenderSection("RelatedTools", required:true)
                </div>
            </div>
           
        </div>
     
    

    View:

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    </div>
    
    @section RelatedTools {
        <div><h1>RelatedTools</h1></div>
    }
    

    So that the html in @section RelatedTools will in the right side,and the html outside @section RelatedTools will in the left side.

    Result: enter image description here