X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Monday, December 1, 2014

MVC override controller methods

As you have seen in my post -  Overriding RazorViewEngine in MVC here in this post also i am trying to override the path of the view but this time by overriding controller rather than creating the custom view engine.

Now lets dive in to the code part -

Here i am going to reuse the controllers and folders created in the last post and I will be creating a new controller named "BaseController.cs" and this will be inherited from "Controller" class. This BaseController is used as a base class for all the controllers like Home,Contact etc.

public class BaseController : Controller
{
     protected override ViewResult View(string ViewName, string masterName, object model)
     {
         ViewResult renderview = null;

         if (Session != null && Session["TestFolder"] != null)
         {
            if (System.IO.File.Exists(Server.MapPath(VirtualPathUtility.ToAbsolute("~/Views" 
                                  + Session["TestFolder"].ToString().Trim() + "/" + ViewName + ".cshtml"))))
            {
                renderview = base.View("~/Views/" + Session["TestFolder"].ToString().Trim()+ "/" + ViewName + ".cshtml"
                                  , masterName, model);
            }
            else
            {
                renderview = base.View("~/Views/Shared/" + ViewName + ".cshtml", masterName, model);
            }
   
         }
         else
         {
             renderview = base.View("~/Views/Shared/" + ViewName + ".cshtml", masterName, model);
         }

         if (renderview != null)
              return renderview;


         return base.View(ViewName, masterName, model);
     }
}

As you can see in the above code i am overriding the method  "Viewof Controller class , which is been called on "return View()" in action. 

Note :  To get the value for "ViewName" parameter in the above method you have to make sure that you will pass the name of the view - return View("yourviewname") 

The above method searches the view in "AllViews" folder (Session["TestFolder"]) and in case view did not found in that location then it tries to search in "/Shared" folder.
For partial Views we have similar method -
protected override PartialViewResult PartialView(string viewName, object model)
{
 return base.PartialView(viewName, model);
}

So the main drawback of this approach is if in the view uses - "@HTML.Partial("partialviewname")" then both of the above methods would not be called then we need to go with approach of overriding razor view engine as I have shown in the last post. 


No comments:

Post a Comment

Comments Section