ASP.NET MVC – Content Result

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:

TIP: Hamlet.xml can be downloaded from using the following link

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!

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *