I'm implementing asp.net core project. I have a method in my controller that should pass a data to a viewcomponent and then I need that data to be displayed in _Layout razor view. Below is what I have tried till now:
public class AccountController : Controller {
public IActionResult Index(string str)
{
_httpContext.HttpContext.Items["Shared"] = str;
Debug.WriteLine("str:" + str);
Debug.WriteLine("HttpContext Index shared:"+_httpContext.HttpContext.Items["Shared"]);
// Use ViewData
ViewData["Shared"] = str;
Debug.WriteLine("ViewData Index shared:" + ViewData["Shared"]);
return View();
}
}
public class MySharedDataViewComponent : ViewComponent
{
private readonly IHttpContextAccessor _httpContext;
public MySharedDataViewComponent(IHttpContextAccessor context)
{
_httpContext = context;
}
public Task<IViewComponentResult> InvokeAsync()
{
Debug.WriteLine("MyShred data:" + _httpContext.HttpContext.Items["Shared"]);
return Task.FromResult<IViewComponentResult>(View(_httpContext.HttpContext.Items["Shared"]));
}
}
In index.cshtml for Account controller:
@model string
<h2>@Model</h2>
In Default.cshtml
@model dynamic
@{
var passedDataFromItems = (Model as string);
var passedDataFromViewData = (ViewData["Shared"] as string);
}
@passedDataFromItems
@passedDataFromViewData
In _Layout I added this:
<div class="col-sm-10 col-8 p-0 m-0 text-left">
@await Component.InvokeAsync("MySharedData")
</div>
And in startup I pasted what you suggested as well.
My problem is in _Layout there isn't any data from ViewComponent to be displayed.