mardi 29 décembre 2015

Render MVC view from ASP.NET

I have two separate projects one in MVC and another in ASP.NET. I have a function in MVC which render a view and convert it into a stream which is working absolutely fine.

I am using this function from ASP.NET using dll to render MVC view from ASP.NET. Problem is razorViewEngine.FindView always return null.

Any kind of help to render MVC view from ASP.NET will save my time as well as save me from rework.

public static Stream RenderView<T>(string controllerName, string viewName, T model, Dictionary<string, object> viewData = null)
        var context = HttpContext.Current;
        var contextBase = new HttpContextWrapper(context);
        var routeData = new RouteData();
        routeData.Values.Add("controller", controllerName);
        var controllerContext = new ControllerContext(contextBase, routeData, new EmptyController());
        var razorViewEngine = new RazorViewEngine();
        var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false);
        var writer = new StringWriter();
        var vdd = new ViewDataDictionary<T>(model);

        if (viewData != null)
            foreach (var d in viewData)
                vdd.Add(d.Key, d.Value);

        var viewContext = new ViewContext(controllerContext, razorViewResult.View, vdd, new TempDataDictionary(), writer);
        razorViewResult.View.Render(viewContext, writer);
        byte[] byteArray = Encoding.UTF8.GetBytes(writer.ToString());
        return new MemoryStream(byteArray);
    class EmptyController : ControllerBase
        protected override void ExecuteCore() { }

Aucun commentaire:

Enregistrer un commentaire