The different types of result types that return by the controller action in order to serve the user request.
Controller:-
The controller is responsible for sending the response to the user based on the user request. The Request/Response flow of mvc is shown below
User Request -> Routing Engine -> Controller -> ViewResult -> ViewEngine -> View
Different Resulttypes return from controller action:-
1.)ViewResult
2)PartialViewResult
3)ContentResult
4)FileContentResult
5)RedirectResult
6)RedirectToRouteResult
7)RedirectResult
8)HttpStatusCodeResult
9)HttpNotFoundResult
10)JsonResult
The above ResultTypes inheriting an abstract class called ActionResult which has an abstract method called ExecuteResult. The ExecuteResult method is override by the above ResultTypes classes. The ExecuteResult responsible for processing the request.
public abstract void ExecuteResult(ControllerContext context);
The controller has convenience methods to return the above resulttypes. Some the methods are
1) View
2)PartialView
3)Json
Example:- The View convenience method creates a System.Web.Mvc.ViewResult object that renders a view to the response.
The user can either use controller convenience method or create an instance of resulttype directly in the controller action. i.e return View()/return new ViewResult()
Example for different result types:-
public ActionResult getView()
{
return View();
}
public ActionResult getpartialView()
{
return PartialView();
}
public ActionResult getContent()
{
//content() returns content to the user
return Content("Hello World!", "text",System.Text.Encoding.UTF8);
}
public ActionResult getfileContent()
{
//string filePath = Path.Combine(@"~/App_Data/", "ErrorLog_" + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt");
string filePath = Path.Combine(@"~/App_Data/", "sampleData.txt");
filePath = Server.MapPath(filePath);
FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read);
byte[] fileData = new byte[fs.Length];
fs.Read(fileData,0,System.Convert.ToInt32(fs.Length));
fs.Close();
return new FileContentResult(fileData, "text");
}
public ActionResult redirecttoAction()
{
return RedirectToAction("About", "Home");
}
public ActionResult redirecttorouteDemo()
{
return RedirectToRoute("testRoute", new { Controller="Home",Action="About", productId = 44 });
}
public ActionResult redirectDemo()
{
return Redirect("http://giri-aspdotnet.com");
}
public ActionResult httpstatusCodeResult()
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound, "The request resource does not exist in the server.");
}
public ActionResult httpnotFoundResult()
{
return new HttpNotFoundResult("File Not Found in mvc4examplesbygiri");
}
public ActionResult getjsonData()
{
//use ajax call to get the reponse as json data
return Json(new { data = "Sample Json Data" });
}
No comments:
Post a Comment