0

Okay so right now in my main controller class I just have each separate thing return a view like:

    public ActionResult Contact()
    {
        return View();

    }

I have this down pat, as it is not very difficult! What I would like to know though, is what else can I do in this actionresult? What other things can be accomplished through this?

Ethan Pieper
  • 57
  • 1
  • 2
  • 5

2 Answers2

3

You could return a hardcoded content instead of a view:

public ActionResult Contact()
{
    return Content("Hello");
}

You could return JSON:

public ActionResult Contact()
{
    return Json(new { Foo = "bar" }, JsonRequestBehavior.AllowGet);
}

You could return javascript:

public ActionResult Contact()
{
    return JavaScript("alert('Hello World');");
}

You could directly stream a file:

public ActionResult Contact()
{
    return File(@"c:\work\foo.pdf", "application/pdf", "foo.pdf");
}

You could return a 404:

public ActionResult Contact()
{
    return HttpNotFound();
}

You could return 401:

public ActionResult Contact()
{
    return new HttpUnauthorizedResult();
}

And if the built-in action results doesn't suit your needs you could always write a custom one. For example one that returns XML:

public class XmlResult : ActionResult
{
    private readonly object _data;
    public XmlResult(object data)
    {
        if (_data == null)
        {
            throw new ArgumentNullException("data");
        }
        _data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "text/xml";
        var serializer = new XmlSerializer(_data.GetType());
        serializer.Serialize(response.OutputStream, _data);
    }
}

and then:

public ActionResult Contact()
{
    return new XmlResult(new { Foo = "Bar" });
}

So as you can see there are plenty of things you could do. The question is: what do you want to do?

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Wow thanks for this! Super helpful. To answer the question at the end though, I don't have any idea what I want to do! I'm doing sort of a final project to teach myself everything I can about MVC3 and related things and I wanted to incorporate more things other than just straight up views. – Ethan Pieper Jul 16 '12 at 17:38
  • Can you add the partialview? Very handy for JavaScript calls. :) – Silvermind Jul 16 '12 at 18:10
0

Usually within the Action on the Controller you'll get data from a data store and return it to the view. If you're asking what types of ActionResults there are, you can find a list of them here.

Community
  • 1
  • 1
Shane Fulmer
  • 7,510
  • 6
  • 35
  • 43