Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell ASP.NET Core view exists from controller?

Sometimes a controller needs to check if a view exists so that it can take some action if it doesn't?

I've seen similar questions like this one Does a view exist in ASP.NET MVC? for prior versions of asp.net mvc but such approaches don't work for ASP.NET Core. I have been unable to locate any documentation on how to do it with ASP.NET Core from inside the controller.

Given the following:

string viewLoc= "~/views/some-folder/some-file.cshtml";

How can the controller determine if the view exists?

like image 408
RonC Avatar asked Jun 07 '16 19:06

RonC


1 Answers

This is how I solved this problem in Asp.Net Core 1.0. Use ICompositeViewEngine. This below is an example.

private readonly ICompositeViewEngine _compositeViewEngine;

public YourController(ICompositeViewEngine compositeViewEngine)
{
    _compositeViewEngine = compositeViewEngine;
}

And then in your Action:

[Route("/location/{name}")]
public IActionResult Location(string name)
{
    var viewName = $"~/Views/Location/{name}.cshtml";
    var result = _compositeViewEngine.GetView("", viewName, false);

    if (result.Success) return View(viewName);

    // or do whatever you want
    return NotFound();
}
like image 128
Vaclav Elias Avatar answered Nov 15 '22 06:11

Vaclav Elias