Sunday, February 3, 2013

Execute Razor Helper Method from Code File

Problem: I really really hate myself when I have to write html syntax in code file using TagBuilder. All those html syntaxes <div>I hate myself </div> don't really belong in class file. It really should be in a html file or in my case some .cshtml file. And yes I am aware that these declarative helper functions in app_code are ultimately converted to classes, however it's much cooler to write html in cshtml file rather than in cs file(Of course it's just my opinion :) )

Solution: It really really is simple. After doing a lot of digging into some source code I came up with this simple solution using BuildManager and some reflection. Here it goes:


public static string RenderHelperMethod(string virtualPathOfSomePage,string functionName, params object[] paramsToPass)
        {

            var typ = BuildManager.GetCompiledType(virtualPathOfSomePage);
            if (typ != null)
            {
                HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current);
                var tm = typ.GetMethod(functionName);
                var inst = Activator.CreateInstance(typ);
               var webpage = inst as System.Web.Mvc.WebViewPage;
                webpage.Context = wrapper;

                var result = tm.Invoke(inst, paramsToPass);
                if (result != null)
                {
                    return result.ToString();
                }

            }

            return null;
        }

BuildManager  provides some other static methods that may interest you. Please dig into this more if you are really interested in doing some research on dynamic compilation and all. And of course don't forget to drop in some links if you find anything more on this topic.