ASP.NET MVC Interview Questions 2 - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
ASP.NET MVC Interview Questions 2

ASP.NET MVC Interview Questions 2

7. What is Routing in ASP.NET MVC?

Answer:

The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. Routing is a pattern matching system that monitors the incoming request and figures out what to do with that request.

Routing helps us to define a URL structure and map the URL with the controller.

Below is the code which shows how the URL structure, mapping with controller and action is defined.

public static void RegisterRoutes(RouteCollection routes)
{
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
}
protected void Application_Start()
{
        RegisterRoutes(RouteTable.Routes);
}

8. Explain attributes based routing in MVC. How to define it?

Answer:

This feature introduces in MVC 5. By using the "Route" attribute we can define URL structure. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

For example in the below code we have decorated the "GotoContact" action with the route attribute. The route attribute says that the "GotoContact" can be invoked using the URL structure "Users/contact".

public class HomeController : Controller
{
       [Route("Users/contact")]
       public ActionResult GotoContact()
       {
           return View();
       }
}

9. How to enable attribute routing in ASP.NET MVC?

Answer:

To enable attribute routing in ASP.NET MVC5 application, we just add a call to routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig.cs file.

public class RouteConfig
{
        public static void RegisterRoutes(RouteCollection routes)
        {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                //enabling attribute routing
                routes.MapMvcAttributeRoutes();
        }
}

10. What is the difference between Routing and URL rewriting?

Answer:

Routing is focused on mapping a URL to a resource while URL rewriting is focused on mapping one URL (new URL) to another URL (old URL).

URL rewriting rewrites your old URL to new one while routing never rewrites your old URL to new one but it maps to the original route.

11. How can we maintain session in MVC?

Answer:

Sessions can be maintained in MVC by three ways:
  • TempData
  • ViewData
  • ViewBag

12. What is the difference between ViewData, ViewBag and TempData?

Answer:

ViewData: 
ViewData helps to maintain data when we move from controller to view. It is derived from the ViewDataDictionary class. It is available for the current request only and also requires typecasting for complex data.

ViewBag:
It also helps to maintain data when we move from controller to view. It uses dynamic keyword internally. It is also available for the current request only and typecasting is not required.

TempData:
It is derived from TempDataDictionary class. Tempdata helps to maintain data when we move from one controller to another controller or from one action to another action. It requires typecasting for complex data.

13. What is Partial View in ASP.NET MVC?

Answer:

Partial view is a reusable view (like user control). A partial view is a view that is rendered within another view which means it can be embedded inside other view.

Partial view can be rendered using Html.Partial(), Html.RenderPartial(), Html.RenderAction() method. 

14. Explain the difference between View and Partial View?

Answer:

View:
  • View contains the layout page.
  • Before any view is rendered, viewstart page is rendered.
  • It is not lightweight as compare to Partial View.
  • View might have markup tag like html, head, title, body etc.
Partial View:
  • Partial view does not contain layout page.
  • We can pass regular view to the render partial method.
  • Partial view is designed specially to render within the view and just because of that it does not consist any mark up.
  • Partial View is lightweight compared to View.
  • Partial view can be embedded inside another view.

15 What are the HTML helpers in ASP.NET MVC?

Answer:

Html helpers are a method that returns a HTML string. HTML helpers help us to render HTML controls in the view. HTML helper does not have an event model and a view state.

We can also create our own HTML Helpers to render more complex content.

There are three types of HTML helpers. 

i. Inline HTML helpers

ii. Built-in HTML helpers
  • Standard HTML helpers
  • Strongly type HTML helpers
  • Templated HTML Helpers
iii. Custom HTML helper

If we want to add HTML textbox on view, below is the HTML helper.
<%= Html.TextBox("Name") %>

16. What is the difference between "HTML.TextBox" and "HTML.TextBoxFor"?

Answer:

HTML.TextBoxFor is strongly type while HTML.TextBox is not, but they both produce same HTML.

1:  @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)

will both produce
<input id="Name" name="Name" type="text" />

Using the typed "TextBoxFor" version allows using compile time checking. So if we change our model then we can check whether there are any errors in your views.

17. How can we do validation in ASP.NET MVC?

Answer:

ASP.NET MVC uses DataAnnotations attributes to implement validations. It is one of the easiest ways to do validation in MVC.

For example, in the code snippet below we have a simple Employee class with a property EmpCode.

This EmpCode property is tagged with a Required data annotation attribute. 

public class Employee
{
    [Required(ErrorMessage="Emp code is required")]
    public string EmpCode
    {
        set;
        get;
    } 
}

In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostEmployee", "Home", FormMethod.Post))
{ %>
    <%=Html.TextBoxFor(m => m.EmpCode)%>
    <%=Html.ValidationMessageFor(m => m.EmpCode)%>
    <input type="submit" value="Submit Employee data" />
<%}%>

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

public ActionResult PostEmployee(Employee obj)
{
    if (ModelState.IsValid)
    {
        obj.Save();
        return View("Thanks");
    }
    else
    {
        return View("Employee");
    }
}

18. What is validation summary?

Answer:

The validation summary is used to display all the error messages in the view. It displays an unordered list of all validation errors in the ModelState dictionary object.

Example:

@Html.ValidationSummary(true) @*//shows model-level errors*@
@Html.ValidationSummary(false) @*//shows model-level and property-level errors*@

25. What is the difference between ActionResult and ViewResult?

Answer: 

In ASP.NET MVC, ActionResult and ViewResult are mainly a return type for Controller Action method.

ActionResult is an abstract class while ViewResult derives from the ActionResult class.

ViewResult can return only ViewResult type. ActionResult can return many type of Result.

If we are returning different type of view dynamically then ActionResult is best things.

Example 1: ActionResult

public ActionResult DynamicView()
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
}

Example 2: ViewResult

public ViewResult Index()
  {     
      return View();
  }

26. What are the Filters in MVC?

Answer:

Filters: 
ASP.NET MVC filter is a custom class where we can write our custom logic to execute before or after Action method execute. Filter can be applied to an action method or controller.

Filter provides feature to add and post action behaviors on controller's action methods.

Types of Filter:
  • Action Filters: Perform some operation before and after an action method execute and implements the IActionFilter attribute.

  • Authorization Filters: It is used to implement authentication and authorization for controller actions and implements the IAuthorizationFilter attribute.

  • Result Filters: Result filters contain logic that are executed before and after a view result is executed and implement the IResultFilter attribute.

  • Exception Filter: We use exception filter to handle errors raised by either our controller or controller action results and implements the IExceptionFilter attribute.

27. What are the ActionFilters in MVC? What are the different types of action filters?

Answer: 

Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties and fields.

ASP.NET MVC provides following action filters:

Output Cache: Output action filter caches the output of a controller action for a specified amount of time.

Handle Error: Handle action filter handles errors raised when a controller action executes.

Authorize: This action filter enables you to restrict access to a particular user or role.

28. What are the ways of handling an Error in MVC?

Answer:

Exception handling is the required part of the each application, whether it is web application or a Window Forms Application.

There are multiple ways to handle exception in ASP.NET MVC. 

1. Using Try catch block
This is the simple ways to handle the exception handling in ASP.NET MVC. When the exception happens the catch block gets executed and it redirect to error view.

2. Override OnException method
The OnException is a void method that takes an argument as an object of ExceptionContext that has all the information about exception. 

We override the "OnException" event of the controller and set the "Result" to the view. This View gets invoked when error occurs in the controller.

3. Using HandleError attribute
ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters.

We can define "HandleError" attributes as shown below.

public class HomeController : Controller
{
        [HandleError()]
        public ActionResult Index()
        {
            throw new Exception("Demo");
        }
}

4. Global Error Handling in MVC
If you want global error handling across the application, then override the "Application_Error" event and redirect the page from the global error.

29. What is Bundling and Minification in MVC?

Answer:

Bundling and Minification concept are introduced in MVC 4 and .NET framework 4.5. Both techniques are used to reduce the number of requests to the server and size of requested CSS and JavaScript, which improve page loading time.

Bundling:
Bundling helps us combine multiple JavaScript and CSS files into a single entity thus minimizing multiple requests into a single request.

Minification:
Minification is technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage.

For example consider following JavaScript code.

Example:

sayHello = function(wish){
    //this is comment
    var msg = "Hello" + wish;
    alert(msg);
}

The above JavaScript will be optimized and minimized into following script.

sayHello=function(n){var t="Hello"+n;alert(t)}

30. What is GET and POST Actions Types?

Answer:

GET - GET is used to request data from a specified resource. With the entire GET request we pass the URL which is compulsory, however it can take the following overloads.

.get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

POST - POST is used to submit data to be processed to a specified resource. With all the POST requests we pass the URL (compulsory) and the data, however it can take following overloads.

.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

    31. What is Scaffolding?

    Answer:

    Scaffolding is the technique for code generation for ASP.NET web application. This technique is used by many MVC frameworks like ASP.NET MVC, Node JS etc for code generation. Using Scaffolding we can reduce the amount of time to develop standard data operation in our project. 

    Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These are called Scaffolding templates.

    32. What is JsonResult in ASP.NET MVC?

    Answer:

    "JSON" (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It provides an efficient mechanism to exchange data between the web browser and the web server.

    The JSON format is an open standard format. The format of data looks very easy to understand and the data object consists of attribute-value pairs.

    JsonResult Class is inherited from the "ActionResult" abstract class. Action methods in controllers return JsonResult that can be used in AJAX application. The JsonResult represents a class that is used to send JSON-formatted content to the response.

    Example:
    public ActionResult Movies()
    {
        Return Json("Avengers!");
    }

    33. What is caching and when to use it?

    Answer:

    Caching is used to enhance the performance of the ASP.NET MVC web application. Caching provides a way of storing frequently accessed data and reusing that data.

    In ASP.NET MVC, OutputCache attribute is used for applying Caching. OutputCaching will store the output of a Controller in memory and if any other request comes for the same, it returns the output from cache result.

    When to use:
    • Avoid caching content which is unique for every user or rarely used.
    • Cache frequently used content.
    • Define a short cache expiration time rather than disabling caching.

    34. What is loose coupling and how is it possible?

    Answer: 

    Loose coupling is a software design where all classes can work independently without relying on each other.

    MVC design pattern enables us to develop application's components independently which allows testing and maintenance of our application easier. 

    Using Dependency Injection, you can develop loosely coupled application's components.

    35. How can we do exception handling in MVC?

    Answer:

    In controller section we can override the "OnException" event and set the "Result" to the view name which we want to invoke when error occurs. In the code below you can see we have set the "Result" to a view named as "Error".

    public class HomeController : Controller
    {
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
            var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");
            filterContext.Result = new ViewResult()
            {
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
            };
        }
    }

    To display above error in view, we use this code.

    @Model.Exception;

    36. What is Layout View?

    Answer:

    ASP.NET MVC layout is like Master page in ASP web form. Using Layout view we maintain a consistent look and feel across all the pages within our web application. Layout may contain common jQuery, CSS file across multiple Views. 

    The Layout view provides the code reusability that eliminates the duplicate code and enhances development speed and allows easy maintenance.
    Following are the auto generated _Layout.cshtml.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - My ASP.NET Application</title>
        @Styles.Render("∼ /Content/css")
        @Scripts.Render("∼ /bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>© @DateTime.Now.Year - My ASP.NET Application</p>
            </footer>
        </div>
        @Scripts.Render("∼ /bundles/jquery")
        @Scripts.Render("∼ /bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>

    The _ViewStart File

    The _ViewStart.cshtml in the Views folder contains the following content.
    @{
        Layout = "∼ /Views/Shared/_Layout.cshtml";
    }
    •  

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.