Blog

ASP.NET MVC - Content Result

By Martin Schaeferle | August 10, 2012

At one extreme, many MVC views consists entirely of static content. But on the opposite end, you have the option to use a ContentResult object to entirely define the content of a Web page within an action method. Strictly speaking, this isn't a feature of MVC views, since there is no view involved in this technique. But when you need to create a Web page that has to be entirely dynamic, this is a good option.

A ContentResult has three properties. Content takes the content you want to display, ContentEncoding defines the encoding of the content, and ContentType tells the browser what the content consists of so that it can render it correctly to the user. Common settings for the content type are text/plain, text/xml, and application/json, but there are many others. For example, say you have some XML data in a file on the server that you want to send to the browser as XML and let the browser deal with displaying it. One way to do this is to read the data from the file in an action method, and use a ContentResult to send it to the browser, like this:
public ContentResult ReadHamlet()
{
string fileName =
Server.MapPath(@"~ContentHamlet.xml");
TextReader tr = new StreamReader(fileName);
string contents = tr.ReadToEnd();
return Content(contents, "text/xml");
}

TIP: Hamlet.xml can be downloaded from iBiblio.org using the following link http://goo.gl/3OIgp.

When you invoke the ReadHamlet action method, the raw XML of the entire play Hamlet displays in the browser. If you use Internet Explorer or another browser that understands XML you can collapse and expand different sections of the play, as shown in Figure 7. Figure 7. Hamlet displayed as XML in the browser.

The important thing to understand about using ContentResult is that you define the entire contents of what the Web page will display. Alternatively, you can provide data for updating a portion of a page, such as when the page makes an Ajax request for JSON data.

Get more training on ASP.NET MVC 2 & 3!



Martin Schaeferle

Martin Schaeferle has taught IT professionals nationwide to develop applications using Visual Basic, Microsoft SQL Server, ASP, and XML. He has been a featured speaker at Microsoft Tech-Ed and the Microsoft NCD Channel Summit, and he specializes in developing Visual Basic database applications, COM-based components, and ASP-based Web sites. In addition to writing and presenting technical training content, Martin is also LearnNowOnline's vice president of technology.


This blog entry was originally posted August 10, 2012 by Martin Schaeferle