get simple data like string in viewcomponent in c#

495 Views Asked by At

Hi I have a viewcomponet that read text from a txt file and i want to show that text in viewcomponent this is my ViewComponents ".cs"

public class MainFooterViewComponent:ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        string lastUpdateTime = System.IO.File.ReadAllText("./last.txt");

        return View(last);
    }
}

And in ".cshtml" i want to show "last"

 <li>last" @last</li>

How can I do that in simple way

1

There are 1 best solutions below

6
On

hhe common way to use view components

Inside of Shared folder you have to crate a Components folder and then MainFooter folder. Create the partial view MainFooter.cshtml there

@model string

<div>

    <p>@Model</p>
</div>

Create class in a Controllers folder

[ViewComponent(Name = "MainFooter")]
public class MainFooterViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
 string lastUpdateTime = System.IO.File.ReadAllText("./last.txt");

return View("MainFooter", lastUpdateTime );
}

Layout or main view

<div> @(await Component.InvokeAsync("MainFooter")) </div>