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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With