kenmtb
kenmtb

Reputation: 69

MVC: trying to understand where ActionResult sends it's data

I have been trying to understand an online tutorial and I am stumped. Can someone please tell me where the text "Hello" is sent to? Is the message sent directly to the browser without being placed on a page?

public class GoHomeController : Controller

{
    public string Index()
    {
        return "Hello";
    }
}

Upvotes: 1

Views: 199

Answers (1)

T McKeown
T McKeown

Reputation: 12847

How's this? Your controller action needs to have a return type of ActionResult, there are many subclasses of this class that allow for various types of responses however you can always influence with brute force if you like. For example"

public ActionResult Index() 
{ 
   Response.Write("hello world");
   return null;
}

The above code writes to the Response stream directly, in my example I return a null. This indicates no ActionResult is needed to be performed by the MVC system, typically this is where the View is specified, the View will be read, parsed and written to the Response stream as well.

But typical controller actions do have return values, for example here is how I could return JSON, remember the View is just an abstraction to allow you to control what is written to the Response stream.

public ActionResult Index() 
{ 

   return Json( new { Message="Hello world"});
}

And then there is the typical ActionResult that directs the output to a .cshtml file:

public ActionResult Index() 
{ 
   return View();
}

This will write to the Response stream using the Index.cshtml file tied to this controller namespace or I could specify the name of the .cshtml:

public ActionResult Index() 
{ 
   return View("HelloWorld");   //<-- looks for HelloWorld.cshtml
}

Upvotes: 2

Related Questions