xandune
xandune

Reputation: 55

ASP.NET Core MVC : load file inside Razor page

I am trying to make the terms and conditions page form my site. However, I am trying to provide the terms and conds page in the language the user prefers like Microsoft (they have this en-US prefix in their URL).

I managed to create separate HTML folders in my wwwroot like terms.en-US.html and terms.fr-CA etc.

I also created a controller named FilesController and it looks like this:

public class FilesController : Controller
{
    [Route("Files/{language}/Terms")]
    public IActionResult Terms(string language)
    {
        ViewData["lang"] = language;
        return View();
    }
} 

And this is the Terms.cshtml file (so far):

@{
   Layout= "_HomeLayout";
}
@Html.Raw(System.IO.File.ReadAllText(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(),"../files/documents/terms_and_conditions/" + @ViewData["lang"] + ".html")));

But obviously it doesnt work. How can I manage this?

PS: the only reason I am trying to add html into cshtml file is to benefit from the layout feature. Otherwise I would have directly return the html file in the controller like this:

public IActionResult Terms()
{
    return File("~/files/documents/terms_and_conditions/tr-TR.html", "text/html");
}

Upvotes: 1

Views: 1054

Answers (1)

Chen
Chen

Reputation: 5174

I use File.ReadAllText to read the path directly and it works fine.

Below is my test code:

View:

@Html.Raw(File.ReadAllText("./wwwroot/files/"+@ViewData["lang"]+".html"))

Controller:

public IActionResult Index(string language)
{
      ViewData["lang"] = language;
      return View();
}

enter image description here

Test Result:

enter image description here

Is this result what you want?

Upvotes: 3

Related Questions