How to pass variable into layout in .NET?
I know that on front-end I can use just @Model... but who sends this
model?
Model is created in the controller/action, and you are passing it to view from your action:
return View(myModel);
For the more accurate answer you need to specify the question or add example code of what you are trying to do, but in general case, you could use:
- Model (ViewModel)
- ViewBag
- ViewData
Please find more information:
Also, View Components is an interesting feature which allows you to create UI widgets.
Update:
In standard layout after login you can see for example "hello a@a" all the time. I wish to have this same with my active wall. Have on top screen name of my wall until I change it or i log out.
For this particular purpose, you could just put the following code directly into your layout/view file:
@using System.Security.Claims
@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> userManager
@{
var userInfo = ((await userManager?.GetUserAsync(User))?.xxx);
// where 'xxx' is any property of ApplicationUser model
}
then you can use @userInfo in the same view to display that info.
User choose wall (just click on the same wall from the list) then name of this wall should be on layout until user log out or change wall.
In this case, JavaScript seems to be a good/easy solution? Or you could read/store that information in browser cache?
As far I'm aware there is no easy way to access session in ASP.NET Core - controller actions are designed to work as stateless, and it's not recommended to override that behaviour (read docs and SO why?).
So if not JavaScript then you could send back the name of a wall to the server and store it in DB, and next you could access it anytime via View Components - I'm using ViewComponents in my project to build and display the main menu, and it's work well for me.
There is a little bit more coding for ViewComponent (you need to create controller and view), but it's flexible feature (I like it) and easy to call in a place where you need it, just
@await Component.InvokeAsync("NameOfCOmponent").