MVC Action Methods Interview Questions

ASP.NET MVC Action Methods Interview Questions

In this article, I will discuss Most Frequently asked MVC Action Methods Interview Questions and Answers.

What are Action methods in ASP.NET MVC?

All public methods of a Controller in ASP.NET MVC application which responds to the incoming URL are considered as Action Methods.

Controller actions are methods defined in the controller class and responsible to perform required operations on the user’s inputs like as form values, query strings values etc. with the help of Model and passing the results back to the View. Asp.net MVC has the following built-in ActionResults Type and Helper methods:

  1. ViewResult – Returns a ViewResult which renders the specified or default view by using controller View() helper method.
  2. PartialViewResult – Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using controller PartialView() helper method.
  3. RedirectResult – Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.
  4. RedirectToRouteResult – Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an action method or specific route entry by using controller RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.
  5. ContentResult – Returns a ContentResult which renders raw text like as “Hello, DotNet Tricks!” by using controller Content() helper method.
  6. JsonResult – Returns a JsonResult which serializes an object in JSON format ( like as “{ “Message”: Hello, World! }”) and renders it by using controller Json() helper method.
  7. JavaScriptResult – Returns a JavaScriptResult which renders a snippet of JavaScript code like as “function hello() { alert(Hello, World!); }” by using controller JavaScript() helper method. This is used only in AJAX scenarios.
  8. FileResult – Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using controller File() helper method.
  9. EmptyResult – Returns no result returned by an action. This has no controller helper method.
  10. HttpNotFoundResult – Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.
  11. HttpUnauthorizedResult – Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code (means “not authorized”) response. This has no controller helper method. This is used for authentication (forms authentication or Windows authentication) to ask the user to log in.
  12. HttpStatusCodeResult – Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.
Important Note: 

All public methods of a Controller in an ASP.NET MVC application are considered as Action Methods by default. If we want our controller to have a Non Action Method, we need to explicitly mark it with NonAction attribute as follows:

What is ActionResult and how is it different from others?

The ActionResult class is the base class for all action results. An action result can be of type ViewResult, JsonResult, RedirectResult and so on. Hence, when your action method returns multiple results based on different conditions, ActionResult is the best choice. Since it can return any type of result.

public ActionResult Index(int id)
{
    if (id == 1)
        return View(); // returns simple ViewResult 
    else if (id == 2)
        return Json(new { result = "1" }, JsonRequestBehavior.AllowGet); // returns JsonResult
    else
        return RedirectToAction("Login"); // returns to Login Page
}
How to make a Non-Action method in ASP.NET MVC?

By default, the ASP.NET MVC framework treats all public methods of a controller class as action methods. If you do not want a public method to be an action method, you must mark that method with the NonActionAttribute attribute.

[NonAction]
public void DoSomething()
{
    // Method logic
}
Can you change the action method name?

We can also change action method name by using ActionName attribute. Now action method will be called by the name defined by the ActionName attribute.

[ActionName("DoAction")]
public ActionResult DoSomething()
{
    //TODO: return View();
}

Now, DoSomething action will be identified and called by the name DoAction.

How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE?

By default, each and every action method can be invoked by any HTTP request (i.e. GET, PUT, POST, and DELETE). But you can restrict an action to be invoked only by a specific HTTP request by applying HttpGet or HttpPost or HttpPut or HttpDelete attribute.

If you want to restrict an action method for HTTP Get request only then decorate it with HttpGet action method selector attribute as given below:

[HttpGet]
public ActionResult Index()
{
    //TODO: 
     return View();
}
How to determine an action method is invoked by HTTP GET or POST?

By using HttpMethod property of HttpRequestBase class, you can find out whether an action is invoked by HTTP GET or POST.

public ActionResult Index(int? id)
{
    if (Request.HttpMethod == "GET")
    {
        //TODO:
    }
    else if (Request.HttpMethod == "POST")
    {
        //TODO:
    }
    else
    {
        //TODO:
    }
    return View();
}
How to determine an AJAX request?

We can determine an AJAX request by using Request.IsAjaxRequest() method. It will return true, if the request is an AJAX request else returns false.

public ActionResult DoSomething()
{
    if (Request.IsAjaxRequest())
    {
        //TODO:
    }
    return View();
}
What is ViewModel in ASP.NET MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Key Points about ViewModel

  1. ViewModel contains fields that are represented in the view (for LabelFor, EditorFor, DisplayFor helpers).
  2. ViewModel can have specific validation rules using data annotations.
  3. ViewModel can have multiple entities or objects from different data models or data source.
SUMMARY

In this article, I try to explain most frequently asked MVC Action Methods Interview Questions and Answers. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *