Skip to content

Instantly share code, notes, and snippets.

@simonjefford
Created June 14, 2012 10:08
Pass HTML to a view rendered by RenderAction
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
namespace renderactiontest.Helpers
{
public static class Helper
{
public static void AddSubElement(this HtmlHelper helper, Func<dynamic, HelperResult> template)
{
helper.ViewContext.TempData["SubContent"] = template(null);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
namespace renderactiontest.Helpers
{
public static class Helper
{
public static void AddSubElement(this HtmlHelper helper, Func<dynamic, HelperResult> template)
{
helper.ViewContext.TempData["SubContent"] = template(null);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace renderactiontest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Index</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<h2>Index</h2>
<p>
Now using render action
<p>
Hey. You asked me to render this
<b>
content
</b>
</p></p>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace renderactiontest.Controllers
{
public class SharedController : Controller
{
//
// GET: /Shared/
public ActionResult Index()
{
return View();
}
}
}
@using renderactiontest.Helpers;
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
Now using render action
@{ Html.AddSubElement(
@<b>
content
</b>
);}
@{ Html.RenderAction("Index", "Shared"); }
</p>
@{
Layout = null;
}
<p>
Hey. You asked me to render this
@TempData["SubContent"]
</p>
@using renderactiontest.Helpers;
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
Now using render action
@{ Html.AddSubElement(
@<b>
content
</b>
);}
@{ Html.RenderAction("Index", "Shared"); }
</p>
@{
Layout = null;
}
<p>
Hey. You asked me to render this
@TempData["SubContent"] // it might be nicer to wrap this in a helper too.
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment