Skip to content

Instantly share code, notes, and snippets.

@bradymholt
Last active November 7, 2017 21:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradymholt/d323c01c119a4ef68dfb to your computer and use it in GitHub Desktop.
Save bradymholt/d323c01c119a4ef68dfb to your computer and use it in GitHub Desktop.
Share Razor Partial View between WebForms and MVC
@model PartialViewModel
<h1>Hello World</h1>
<p>
I was rendered from a <strong>@Model.Source</strong>!
</p>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
//Reference: http://stackoverflow.com/a/1074061/626911
public class RazorPartialBridge
{
public class WebFormShimController : Controller { }
public static void RenderPartial(string partialName, object model)
{
//get a wrapper for the legacy WebForm context
var httpCtx = new HttpContextWrapper(System.Web.HttpContext.Current);
//create a mock route that points to the empty controller
var rt = new RouteData();
rt.Values.Add("controller", "WebFormShimController");
//create a controller context for the route and http context
var ctx = new ControllerContext(
new RequestContext(httpCtx, rt), new WebFormShimController());
//find the partial view using the viewengine
var view = ViewEngines.Engines.FindPartialView(ctx, partialName).View;
//create a view context and assign the model
var vctx = new ViewContext(ctx, view,
new ViewDataDictionary { Model = model },
new TempDataDictionary(), httpCtx.Response.Output);
//render the partial view
view.Render(vctx, System.Web.HttpContext.Current.Response.Output);
}
}
<%@ Page Title="Demo" Language="C#"
AutoEventWireup="true" Inherits="Demo" Codebehind="Demo.aspx.cs" %>
<html>
<head></head>
<body>
<% RazorPartialBridge.RenderPartial("_Partial", new PartialViewModel() { Source = "ASPX Page" }) %>
</body>
</html>
<html>
<head></head>
<body>
@{ Html.RenderPartial("_Partial", new PartialViewModel() { Source = "Razor View" }); }
</body>
</html>
@maria-mcdorman
Copy link

Well this is intriguing but I'm having trouble putting it all together. Do you have an MVC project that works? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment