Controller actions return the ActionResult and it's possible to return kinds of results based on what we want in the output, let’s consider for types of a result in my example in this article.
ActionResult: it just Initializes a new instance of the ActionResult class. ActionResult is the base class for other types of action.
//Action Result
public ActionResult Index()
{
return Content("this is the route of the application defined in Gloabal.asax");
}
public ActionResult ActionResult()
{
return View();
}
//returns a hard coded content
public ActionResult ActionResult2()
{
return Content("this is the content of ActionResult, you can return any text by using it!");
}
//returns to another action
public ActionResult ActionResult3()
{
return RedirectToAction("ActionResult2");
}
//returns to the Route acion
public ActionResult ActionResult4()
{
return RedirectToRoute("Index");
}
public ActionResult ActionResult5()
{
return File("Silverlight.js", "text/javascript");
}
ViewResult: It returned as a controller action and Renders a specified view to the response stream
//View Result
public ViewResult ViewResult(string name)
{
if (name == null) throw new ArgumentNullException("name");
name = "Ehsan";
return View("ViewResult", name);
}
PartialViewResult: renders a specified partial view to the response stream
public ActionResult PartialViewResult()
{
return PartialView("PartialView");
}
public PartialViewResult PostMyForm(SampleModel model)
{
if (ModelState.IsValid)
{
//TODO: something with model data
}
return PartialView("_UserPartialView", model);
}
ContentResult: The content result lets you define whatever content you wish to return. You can just use the ContentResult to return a plain string, Writes content to the response stream without requiring a view
public ContentResult ContentResult()
{
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
}
public ContentResult ContentResult2()
{
string fileName =
Server.MapPath(@"~\Content\Ehsan.xml");
TextReader tr = new StreamReader(fileName);
string contents = tr.ReadToEnd();
return Content(contents, "text/xml");
}
EmptyResult: it just returns An empty response
public ActionResult StalemateResult()
{
return new EmptyResult();
}
FileResult: It used to send files as the response. And in the case of sending the file by name you should use FilePathResult
public FileStreamResult GetFile()
{
const string name = "Ehsan.txt";
var info = new FileInfo(name);
if (!info.Exists)
{
using (var writer = info.CreateText())
{
//Do somthings
}
}
return File(info.OpenRead(), "text/plain");
}
HttpNotFoundResult: it's the same 404 not found
//HttpNotFound
public ActionResult Details(int id)
{
var somthing = "get somthing from repository!";
if (somthing == null)
{
return new HttpNotFoundResult("Sorry, Not Found");
}
else
{
return View("Details");
}
}
HttpUnauthorizedResult: 401 Error
public new void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
else
{
//do somthing else
}
}
JavaScriptResult: It used to return a javascript by action! it has the ContentType hardcoded to "application/x-javascript" and just writes out the Script property.
public JavaScriptResult JavaScriptResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/x-javascript";
return View();
}
public JavaScriptResult TestJavaScript()
{
string s = "$('#divResultText').html('JavaScript Passed');";
return JavaScript(s);
}
JsonResult: it uses a hardcoded JavaScriptSerializer to serialize the JSON data
public JsonResult JsonResult()
{
return Json("this will be downloaded if you wait a sec!", JsonRequestBehavior.AllowGet);
}
public ActionResult JsonResult2(Guid roleId)
{
var actions = Enumerable.Range(1, 5).Select(x => x.ToString(CultureInfo.InvariantCulture)).ToList();
return Json(actions);
}
public JsonResult JsonResult3()
{
var lists = new List<ListItem>() {
new ListItem() { Value = "2", Text = "NONONO" },
new ListItem() { Value = "3", Text = "YESYESYES" }
};
return Json(lists);
}
RedirectToResult: Performs an HTTP redirection to a specified URL
public ActionResult Index()
{
return Redirect("http://www.google.com");
}
RedirectToRouteResult: Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (!UserIsAuthenticated())
{
// Redirect to login page
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Login" }
});
}
}
FilePathResult: Returns a file to the client
public ActionResult FilePathResult()
{
foreach (string upload in Request.Files)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Images/";
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(path, filename));
}
return View();
}