Tech blog

Solving problems

About
Contact

Archive for the ‘Render’ tag

ASP .NET MVC: How to render View into a string

leave a comment

Sometimes a developer needs to render a View as string. Practical scenario would be to create an obvious View and send it via e-mail instead displaying it in browser. Here is a simple way to extract content from a rendered View:

Implement RenderViewToString method

public class HomeController : Controller
{
  protected string RenderViewToString(string viewName, object model)
  {
    string result = null;
    var view = ViewEngines.Engines.FindView(this.ControllerContext, viewName, null).View;
    if (view != null)
    {
      var sb = new StringBuilder();
      using (var writer = new StringWriter(sb))
      {
        var viewContext = new ViewContext(this.ControllerContext, view,
              new ViewDataDictionary(model), new TempDataDictionary(), writer);
        view.Render(viewContext, writer);
        writer.Flush();
      }
      result = sb.ToString();
    }
    return result;
  }
}

Call it in your action method

//Somewhere in HomeController...
public ActionResult Index()
{
    //Render a View named 'Email' to string variable named 'content'
    //Second parameter (model) can be null
    string content = RenderViewToString("Email", new EmailModel());

    //Do something with the content, e.g. send it to e-mail

    //This does nothing to do with rendered string
    return View();
}
VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

March 31st, 2010 at 10:38 pm

WriteableBitmap does not Render()?!

leave a comment

We spent quite some time working on a Silverlight deep zoom application. Like in other projects, a problem appears sooner or later. This time with the WriteableBitmap that couldn’t take screenshot of a basic shape.

//Simple ellipse (green circle)
Ellipse element = new Ellipse()
{
	Width = 50,
	Height = 50,
	Fill = new SolidColorBrush(Colors.Green)
};

//WriteableBitmap current = new WriteableBitmap(50, 50);
//current.Render(element, new MatrixTransform()); //DOES NOT WORK!!! - renders blank transparent image

//But with the constructor works fine
WriteableBitmap bitmap = new WriteableBitmap(element, new MatrixTransform());

//Ellipse captured as raster image painted on a panel's background
Grid grid = new Grid()
{
	Width = 50,
	Height = 50,
	Background = new ImageBrush() { ImageSource = bitmap }
};

Summary for the Render() method says: “Renders an element within the bitmap.”
Render() method didn’t output required result but using constructor instead of the method did do the job. Input parameters were the same.

Maybe Render() method do something else, maybe it is a problem with Vista 64-bit…

Anyway, WriteableBitmap is very useful in Silverlight 3, luckily it works.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Written by developer

December 9th, 2009 at 5:36 pm