Does a view exist in ASP.NET MVC?

前端 未结 7 753
粉色の甜心
粉色の甜心 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条回答
  •  萌比男神i
    2020-11-28 10:50

    If you want to re-use this across multiple controller actions, building on the solution given by Dave, you can define a custom view result as follows:

    public class CustomViewResult : ViewResult
    {
        protected override ViewEngineResult FindView(ControllerContext context)
        {
            string name = SomeMethodToGetViewName();
    
            ViewEngineResult result = ViewEngines.Engines.FindView(context, name, null);
    
            if (result.View != null)
            {
                return result;
            }
    
            return base.FindView(context);
        }
    
        ...
    }
    

    Then in your action simply return an instance of your custom view:

    public ActionResult Index()
    { 
        return new CustomViewResult();
    }
    

提交回复
热议问题