0

I am trying to send retrieved data from database in a controller to the '_Layout.cshtml' file. But not sure how can I pass the data from the controller to the _Layout.cshtml. Does anyone know how to do it?

3 Answers3

1

For passing data from Controller to View, there are three options below:

  • Strongly typed data: viewmodel
  • Weakly typed data

    • ViewData (ViewDataAttribute)
    • ViewBag

If you want to return different value from Controller to _Layout.cshtml, you could try ViewData.

Example:

  1. Model

    public class UserVM
    {
        public int UserId { get; set; }
        public string Value { get; set; }
    }
    
  2. Layout.cshtml

    @using Microsoft.AspNetCore.Hosting
    @{ 
        var users = ViewData["Users"] as List<UserVM>;
    }
    <!DOCTYPE html>
    <html>
    <body>
    
        <div class="container">
            <partial name="_CookieConsentPartial" />
            <main role="main" class="pb-3">
                @foreach (var user in users)
                {
                    <div>@user.Value</div>
                }
                @RenderBody()
            </main>
        </div>    
    
        @RenderSection("Scripts", required: false)
    </body>
    </html>
    
  3. Controller Action

    public async Task<IActionResult> Index()
    {
        ViewData["Users"] = new List<UserVM> {
            new UserVM{ UserId = 1, Value = "Tom"},
            new UserVM{ UserId = 2, Value = "Jack"},
            new UserVM{ UserId = 3, Value = "Vicky"}
        };            
        return View();
    }
    
Edward
  • 28,296
  • 11
  • 76
  • 121
0

Try using ViewData or ViewBag to pass data to dropdown. The below link might help Link

Ajoe
  • 1,397
  • 4
  • 19
  • 48
  • But '_Layout.cshtml' view doesn't have any controller –  Aug 04 '19 at 04:07
  • @JatinKumar _Layout.cshtml does not need to have a `Controller` if you are using Templating, just pass the `ViewBag`, in all the `Controller` of all the pages that use the _Layout. – Bosco Aug 05 '19 at 05:22
0

You can create some service and inject in your layout.cshtml

Something like this

@inject MyService myService

@if(await myService.GetListOfData()) {
  // display data here
}

So in your serivce you can write like the nomarl service

public class MyService
{
    private readonly IRepository<ObjectDTO> _repo;
    public MyService(IRepository<ObjectDTO> repo)
    {
        _repo = repo;
    }

    public async Task<bool> GetListOfData()
    {
        var data = await _repo.Where(); // something
        return data;
    }
}
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60