ActionResult tutorial with examples in .Net MVC

ActionResult is a class in the .NET MVC framework that represents the result of a controller action. It's essentially a way to tell the framework what to do next after a user makes a request to the server. Here are a few examples of what an ActionResult might be used for:

  • Return a view to the user (e.g. a webpage)
  • Return JSON data to the user (e.g. an API response)
  • Redirect the user to a different page or URL
  • Return a file to the user (e.g. a download)

Examples of ActionResult in .NET MVC

Here are some code examples of how you might use ActionResult in a .NET MVC application:

Example 1: Returning a view

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

In this example, we're returning a ViewResult (a type of ActionResult) that will render the Index view. This is a common pattern for returning HTML to the user.

Example 2: Returning JSON data

public ActionResult GetSomeData()
{
    var data = new { Name = "John", Age = 30 };
    return Json(data, JsonRequestBehavior.AllowGet);
}

In this example, we're returning a JsonResult (another type of ActionResult) that will serialize the data object to JSON and return it to the user. This is a common pattern for building APIs.

Example 3: Redirecting the user

public ActionResult RedirectToHome()
{
    return RedirectToAction("Index", "Home");
}

In this example, we're returning a RedirectToRouteResult (yet another type of ActionResult) that will redirect the user to the Index action on the Home controller.

Example 4: Returning a file

public ActionResult DownloadFile()
{
    byte[] fileContents = GetFileContents();
    return File(fileContents, "application/pdf", "myfile.pdf");
}

In this example, we're returning a FileStreamResult (one more type of ActionResult) that will return a file to the user as a download. This is a common pattern for serving static files from a server.

Example 5: Returning a custom response

public ActionResult CustomResponse()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StringContent("This is a custom response.");
    response.Headers.CacheControl = new CacheControlHeaderValue()
    {
        Public = true,
        MaxAge = TimeSpan.FromMinutes(30)
    };
    return new HttpResponseMessageResult(response);
}

In this example, we're returning a custom HttpResponseMessage (not a type of ActionResult, but we can use it in conjunction with HttpResponseMessageResult) that we've built from scratch. This can be useful for building custom responses that don't fit neatly into one of the existing ActionResult types.

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
3 + 4 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice