In ASP.NET MVC, action methods are responsible for responding to HTTP requests. These methods can be categorized based on their functionality and the HTTP verbs they respond to. Here are the different types of methods commonly used in ASP.NET MVC:
1. Standard Action Methods
These methods correspond to the standard HTTP verbs and are used to handle incoming requests. The most common HTTP verbs are GET, POST, PUT, DELETE, etc.
HttpGet
Handles GET requests, typically used to retrieve data and display views.
[HttpGet]
public ActionResult Index()
{
return View();
}
HttpPost
Handles POST requests, typically used to submit data to the server.
[HttpPost]
public ActionResult Create(MyModel model)
{
if (ModelState.IsValid)
{
// Process data
return RedirectToAction("Index");
}
return View(model);
}
HttpPut
Handles PUT requests, typically used to update existing data.
[HttpPut]
public ActionResult Update(int id, MyModel model)
{
if (ModelState.IsValid)
{
// Update data
return RedirectToAction("Index");
}
return View(model);
}
HttpDelete
Handles DELETE requests, typically used to delete data.
[HttpDelete]
public ActionResult Delete(int id)
{
// Delete data
return RedirectToAction("Index");
}
2. JsonResult Methods
These methods return JSON-formatted data, useful for AJAX calls.
public JsonResult GetJsonData()
{
var data = new { Name = "John", Age = 30 };
return Json(data, JsonRequestBehavior.AllowGet);
}
3. ContentResult Methods
These methods return raw content, such as strings or HTML.
public ContentResult GetContent()
{
return Content("Hello, World!");
}
4. FileResult Methods
These methods return files to the client, such as images or documents.
public FileResult GetFile()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(@"path\to\file.pdf");
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "file.pdf");
}
5. PartialViewResult Methods
These methods return partial views, which are fragments of HTML intended to be included in other views.
public PartialViewResult GetPartialView()
{
return PartialView("_PartialViewName");
}
6. RedirectResult Methods
These methods redirect the client to a different URL.
Redirect
Redirects to a specified URL.
public RedirectResult RedirectToGoogle()
{
return Redirect("https://www.google.com");
}
7. ViewResult Methods
These methods return views to the client.
public ViewResult GetView()
{
return View();
}
8. HttpStatusCodeResult Methods
These methods return HTTP status codes, useful for signaling errors.
public HttpStatusCodeResult UnauthorizedAccess()
{
return new HttpStatusCodeResult(401, "Unauthorized");
}
Specialized Action Methods with Attributes
ActionName
Allows specifying a different action name than the method name.
[ActionName("MySpecialAction")]
public ActionResult SpecialAction()
{
return View();
}
NonAction
Indicates that a method is not an action method.
[NonAction]
public void HelperMethod()
{
// This is not an action method
}