Friday 11 May 2018

MVC Questions

MVC is a

  • a useful way to organize code , markup and control flow
  • easy to learn
  • designed to help you build and maintain software better


MVC solves Separation of Concerns problem with introduction of below things

  • Models - Data and Business Logic
  • Views - Presentation and UI 
  • Controllers - User actions and Control Flow 
ActionResults: 
ActionResult is an abstract parent class from which ViewResult class has been derived. Following are different response types whcih can be send to end user.


  • ViewResult - Renders a specified view to the response stream
  • PartialViewResult - Renders a specified partial view to the response stream
  • EmptyResult - An empty response is returned
  • RedirectResult - Performs an HTTP redirection to a specified URL
  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  • JsonResult - Serializes a given object to JSON format
  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  • ContentResult - Writes content to the response stream without requiring a view
  • FileContentResult - Returns a file to the client
  • FileStreamResult - Returns a file to the client, which is provided by a Stream
  • FilePathResult - Returns a file to the client


Questions
I have created a controller method foo() but i want to call view bar when this method is called. How to achieve it 
Ans: In the foo method , while you are returning view pass parameter name of view  
Example : View('Bar');



Difference between ActionResult and ViewResult

public ActionResult Index()
{
      return View(); // this is a view result class
}

The above code means that you are returning a “ViewResult” object and due to polymorphism, this object is automatically type casted to the parent class type, i.e., “ActionResult”.

In polymorphism, the parent class object can point towards any one of its child class objects at runtime. For example, in the below code snippet, we have parent “Customer” class which is inherited by “GoldCustomer” and “SilverCustomer” class


public class Customer
{}

public class GoldCustomer : Customer
{}

public class SilverCustomer : Customer
{}

So down the line, later during runtime, your parent “Customer” object can point to any one of the child objects, i.e., “GoldCustomer” or “SilverCustomer”.

Customer obj = new Customer(); obj = new GoldCustomer(); obj = new SilverCustomer();

In MVC when request is sent the response can be anything like HTTP Response, Json Response etc..

MVC Team has created a general class called ActionResult which can be further inherited from different type of result