Does a view exist in ASP.NET MVC?

前端 未结 7 751
粉色の甜心
粉色の甜心 2020-11-28 09:59

Is it possible to determine if a specific view name exists from within a controller before rendering the view?

I have a requirement to dynamically determine the name

7条回答
  •  眼角桃花
    2020-11-28 10:37

    In asp.net core 2.x the ViewEngines property no longer exists so we have to use the ICompositeViewEngine service. This a variant of the accepted answer using dependency injection:

    public class DemoController : Controller
    {
        private readonly IViewEngine _viewEngine;
    
        public DemoController(ICompositeViewEngine viewEngine)
        {
            _viewEngine = viewEngine;
        }
    
        private bool ViewExists(string name)
        {
            ViewEngineResult viewEngineResult = _viewEngine.FindView(ControllerContext, name, true);
            return viewEngineResult?.View != null;
        }
    
        public ActionResult Index() ...
    }
    

    For the curious: The base interface IViewEngine is not registered as a service so we must inject ICompositeViewEngine instead. The FindView() method however is provided by IViewEngine so the member variable may use the base interface.

提交回复
热议问题