Reputation: 199
I currently working for the UI part, I would like to create a template html to use it globally for every pages.
I would like to know how to pass a static text string to view components:
ViewComponent/PageHeaderViewComponent.cs
public class InvokeRequest
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
public string E { get; set; }
}
[ViewComponent(Name = "PageHeader")]
public class PageHeaderViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(InvokeRequest request)
{
return View("Index", request);
}
}
Views/Shared/Components/PageHeader/Index.cshtml
:
@model string
<div id="SomeTemplateTest">
<p>@Model.A</p>
<h1>@Model.B</h1>
<h1>@Model.C</h1>
<h1>@Model.D</h1>
</div>
Views/Shared/_Layout.cshtml
<body>
...
@await Component.InvokeAsync("PageHeader", new InvokeRequest(){ A = Model.A, B = "B", C = Model.C, D = Model.D, E = "2" })
...
</body>
Upvotes: 0
Views: 92
Reputation: 8411
Only little modification of your codes will work. You can try the following:
ViewComponent/PageHeaderViewComponent.cs
the same as yours
Views/Shared/Components/PageHeader/Index.cshtml
.change the string
to InvokeRequest
@model WebApplication76.ViewComponents.InvokeRequest
<div id="SomeTemplateTest">
<p>@Model.A</p>
<h1>@Model.B</h1>
<h1>@Model.C</h1>
<h1>@Model.D</h1>
</div>
Views/Shared/Components/PageHeader/Index.cshtml
. Also addInvokeRequest
as @model
@model WebApplication76.ViewComponents.InvokeRequest
@using WebApplication76.ViewComponents; //here you also need to refence the view components invoke method namespace
...
<body>
...
@await Component.InvokeAsync("PageHeader", new InvokeRequest(){ A = Model.A, B = "B", C = Model.C, D = Model.D, E = "2" })
...
</body>
Controllers/HomeController.cs
. you need to pass model value to the main page you visit.
public IActionResult Index()
{
var model= new InvokeRequest() { A="A",C="C",D="D"};
return View(model);
}
An easy way to auto fix unreferenced item
Upvotes: 1