Render partial view to string with controller context in MVC


In this post we will learn how to render partial view to string using razor view engine in mvc.

In some cases we need to render our view or partial view to string and return as string then we will use it to render inside any containers.

Example 1: To send e-mail with HTML content.

Example 2: To send HTML data in string from the API’s or as service response

Example 3: To update the user with customized alerts.

Example 4: To update the page with ajax calls

So it is important to learn how to render view or partial view to string.

First we need to prepare partial view with data, for this we need to prepare some data object as follows:

Product
public class Products
{
public List<Product> GetProducts()
{
return new List<Product>()
{
new Product{ Id=1,Name=“F&D E200 (2.0 Channel)”,Price=849,Description=“F&D’s E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.”,ImagePath=“/Content/Images/1.jpeg”},
new Product{ Id=2,Name=“F&D F203G Laptop Speakers (2.1 Channel)”,Price=1289,Description=“2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis”,ImagePath=“/Content/Images/2.jpeg”},
//new Product{ Id=3,Name=”Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…”,Price=199,Description=”Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.”,ImagePath=”/Content/Images/3.jpeg”},
new Product{ Id=4,Name=“Portronics Pure Sound Portable Speaker (2.0 Channel)”,Price=1165,Description=“8 hrs Battery Life,Satellites”,ImagePath=“/Content/Images/4.jpeg”},
new Product{ Id=5,Name=“Philips DSP 2800 Home Audio (5.1 Channel)”,Price=2980,Description=“2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis”,ImagePath=“/Content/Images/5.jpeg”},
//new Product{ Id=6,Name=”Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)”,Price=675,Description=”2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket”,ImagePath=”/Content/Images/6.jpeg”},
new Product{ Id=7,Name=“JBL Charge Speaker (Single Unit Channel)”,Price=6749,Description=“20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish”,ImagePath=“/Content/Images/7.jpeg”},
new Product{ Id=8,Name=“Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…”,Price=649,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/8.jpeg”},
new Product{ Id=9,Name=“Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)”,Price=125,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/9.jpeg”},
new Product{ Id=10,Name=“Lenovo Portable Speaker M0520 (2.0 Channel)”,Price=812,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/10.jpeg”}
};
}
}

Then add a partial view in shared folder as follows:

_ProductBox partial view
@model IEnumerable<MVCControls.Models.Product>

@foreach (var product in Model)
{
<div style=”width: 200px; height: 250px; border: 1px #ffd926 solid; padding: 15px; float: left; overflow: hidden; overflow-wrap: break-word; overflow-y: hidden; “>
<div>
<img src=”@product.ImagePath alt=”@product.Name />
</div>
<div style=”font-weight:bold;“>
<strong>@Html.Label(“Name”):</strong> @product.Name
</div>
<div style=”color:green;“>
<strong>@Html.Label(“Price”):</strong> @product.Price
</div>
<div style=”color:brown;“>
<strong>@Html.Label(“Description”):</strong> @product.Description
</div>
</div>
}

then add an action method in controller

Action Method
public ActionResult RenderPartialViewToString()
{
string result = string.Empty;
//get view name from controller context
//var viewName = this.ControllerContext.RouteData.GetRequiredString(“action”);
//get view name directly
var viewName = “_ProductBox”;
ViewData.Model = new Products().GetProducts();
using (var sw = new System.IO.StringWriter())
{
ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
result = sw.GetStringBuilder().ToString();
}
return View(new ProductCatalog() { Catalog = result });
}

Then add view for this action method

View
@model MVCControls.Models.ProductCatalog
@{
Layout = null;
}<!DOCTYPE html>

<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>RenderPartialViewToString</title>
</head>
<body>
<div>
<div style=”padding: 5px;width:850px;margin:0px auto;“>
@Html.Raw(Model.Catalog)
</div>
</div>
</body>
</html>

Now rebuild the application and run

Output:

image

Advertisements