ActionResult
Remarks#
An ActionResult
is best though of as an web endpoint in MVC. Ever ActionResult method can be reached by typing in the appropriate web address as configured by your Routing engine.
Return a View Page
This ActionResult returns a Razor view page. Under the standard routing template this ActionResult method would be reached at https://localhost/about/me
The View will be looked for automatically in your site at ~/Views/About/Me.cshtml
public class AboutController : Controller
{
public ActionResult Me()
{
return View();
}
}
Return a File
An ActionResult
can return FileContentResult
by specifying file path and file type based from extension definition, known as MIME type.
The MIME type can be set automatically depending on file type using GetMimeMapping
method, or defined manually in proper format, e.g. “text/plain”.
Since FileContentResult
requires a byte array to be returned as a file stream, System.IO.File.ReadAllBytes
can be used to read file contents as byte array before sending requested file.
public class FileController : Controller
{
public ActionResult DownloadFile(String fileName)
{
String file = Server.MapPath("~/ParentDir/ChildDir" + fileName);
String mimeType = MimeMapping.GetMimeMapping(path);
byte[] stream = System.IO.File.ReadAllBytes(file);
return File(stream, mimeType);
}
}
Return a Json
Action result can return Json.
1.Returning Json to transmit json in ActionResult
public class HomeController : Controller
{
public ActionResult HelloJson()
{
return Json(new {message1="Hello", message2 ="World"});
}
}
2.Returning Content to transmit json in ActionResult
public class HomeController : Controller
{
public ActionResult HelloJson()
{
return Content("Hello World", "application/json");
}
}