A controller action is a method on a controller that gets called when you enter a particular URL in your browser address bar. For example, you make a request for the following URL.
http://localhost:58379/Author/Edit/3
In this case, the Edit()
action method is called on the AuthorController
.
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Author author = db.Authors.Find(id);
if (author == null)
{
return HttpNotFound();
}
return View(author);
}
A controller action returns an action result in response to a browser request. The ASP.NET MVC framework supports several types of action results including:
All of these action results inherit from the base ActionResult class, and mostly a controller action returns a ViewResult.
Normally, you do not return an action result directly, instead, you can call one of the following methods of the Controller base class:
For example, the Index()
action in AuthorController
does not return a ViewResult()
. Instead, the View()
method of the Controller base class is called.
public ActionResult Index()
{
return View(db.Authors.ToList());
}
So, if you want to return a View to the browser, you call the View()
method. If you want to redirect the user from one controller action to another, you call the RedirectToAction()
method.
public ActionResult Create([Bind(Include = "AuthorId,FirstName,LastName,BirthDate")] Author author)
{
try
{
if (ModelState.IsValid)
{
db.Authors.Add(author);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(author);
}
The Create
action in AuthorController
either redirects the user to the Index()
action or displays a view depending on whether the model state is valid.