wolfgang ziegler


„make stuff and blog about it“

MVC Controllers returning Text or XML

November 25, 2012

If you have an ASP.NET MVC Controller and you want to return just plain and simple text from it, there is an easy solution that does not require creating a dedicated View for this Controller.

The method Content provided by the Controller class handles that scenario and creates a ContentResult (derived from ActionResult) for you.

   1: public class HomeController : Controller
   2: {
   3:   public ActionResult Index()
   4:   {
   5:     return Content("Hello MVC!");
   6:   }
   7: }

An even simpler approach is to change the return value of you controller method to String if you just want to return plain text.

   1: public class HomeController : Controller
   2: {
   3:   public string Index()
   4:   {
   5:     return "Hello MVC!";
   6:   }
   7: }

Both alternatives result in the same output.

image

If you want to return XML directly from you controller you have to stick to the first alternative and set the content type accordingly.

   1: public class HomeController : Controller
   2: {
   3:   public ActionResult Index()
   4:   {
   5:     return Content("<xml>Hello MVC</xml>", "text/xml");
   6:   }
   7: }

The output in your web browser will be as expected.

image

You can go even further and return some static HTML using this approach, even though I would strongly discourage you from doing so and rather go through the traditional View approach. Nonetheless – you can, and here is how you do it:

   1: public class HomeController : Controller
   2: {
   3:   public ActionResult Index()
   4:   {
   5:     return Content("<!DOCTYPE html><html><h1>Hello MVC</h1></html>", "text/html");
   6:   }

Resulting in: image