Most Asked ASP.NET MVC Questions and Answers Part-3


  1. Explain the concept of MVC Scaffolding?
ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.
Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These templates are called Scaffold templates and allow you to quickly build a functional data-driven Website.


Scaffolding Templates:

Create: It creates a View that helps in creating a new record for the Model. It automatically generates a label and input field for each property in the Model.
Delete: It creates a list of records from the model collection along with the delete link with delete record.
Details: It generates a view that displays the label and an input field of the each property of the Model in the MVC framework.
Edit: It creates a View with a form that helps in editing the current Model. It also generates a form with label and field for each property of the model.
List: It generally creates a View with the help of a HTML table that lists the Models from the Model Collection. It also generates a HTML table column for each property of the Model.

  1. What is the difference between ActionResult and ViewResult?
  • ActionResult is an abstract class while ViewResult derives from the ActionResult class.
  • ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
  • ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of views dynamically, ActionResult is the best thing. For example in the below code snippet, you can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.
public ActionResult DynamicView()

{

   if (IsHtmlView)

     return View(); // returns simple ViewResult

   else

     return Json(); // returns JsonResult view

}


  1. What is Route Constraints in MVC?

This is very necessary for when we want to add a specific constraint to our URL.  So, we want to set some constraint string after our host name. Fine, let's see how to implement it.
It's very simple to implement, just open the RouteConfig.cs file and you will find the routing definition in that. And modify the routing entry as in the following. We will see that we have added “abc” before.


Controller name, now when we browse we need to specify the string in the URL, as in the following:

 

  1. What is Output Caching in MVC?
The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic etc.
OutputCache label has a "Location" attribute and it is fully controllable. Its default value is "Any", however there are the following locations available; as of now, we can use any one.
Any
Client
Downstream
Server
None
ServerAndClient

  1. What is the use of Keep and Peek in “TempData”?
Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.
@TempData["MyData"];
TempData.Keep("MyData");
 The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek("MyData ").ToString();

  1. What is Bundling and Minification in MVC?
Bundling and minification are two new techniques introduced to improve request load time. It improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript).
Bundling: It lets us combine multiple JavaScript (.js) files or multiple cascading style sheet (.css) files so that they can be downloaded as a unit, rather than making individual HTTP requests.
Minification: It squeezes out whitespace and performs other types of compression to make the downloaded files as small as possible. At runtime, the process identifies the user agent, for example IE, Mozilla, etc. and then removes whatever is specific to Mozilla when the request comes from IE.

  1. What is Validation Summary in MVC?
The ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages. The following figure shows how ValidationSummary displays the error messages.

  1. What are the Folders in MVC application solutions?
When you create a project a folder structure gets created by default under the name of your project which can be seen in solution explorer. Below I will give you a brief explanation of what these folders are for.
Model: This folder contains classes that is used to provide data. These classes can contain data that is retrieved from the database or data inserted in the form by the user to update the database.
Controllers: These are the classes which will perform the action invoked by the user. These classes contains methods known as "Actions" which responds to the user action accordingly.
Views: These are simple pages which uses the model class data to populate the HTML controls and renders it to the client browser.
App_Start: Contains Classes such as FilterConfig, RoutesConfig, WebApiConfig. As of now we need to understand the RouteConfig class. This class contains the default format of the URL that should be supplied in the browser to navigate to a specified page.


  1. If we have multiple filters, what’s the sequence for execution?
Authorization filters
Action filters
Response filters
Exception filters

  1. What is ViewStart?
Razor View Engine introduced a new layout named _ViewStart which is applied on all view automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view and merges them.
Example of Viewstart:
@ { 

    Layout = "~/Views/Shared/_v1.cshtml"; 

} < !DOCTYPE html > 

    < html > 

    < head > 

    < meta name = "viewport" 

content = "width=device-width" / > 

    < title > ViewStart < /title> < /head> < body > 

    < /body> < /html> 

  1. What is JsonResultType in MVC?
Action methods on controllers return JsonResult (JavaScript Object Notation result) that can be used in an AJAX application. This class is inherited from the "ActionResult" abstract class. Here Json is provided one argument which must be serializable. The JSON result object that serializes the specified object to JSON format.
public JsonResult JsonResultTest() 

{ 

    return Json("Hello My Friend!"); 

}  

  1. What are the Difference between ViewBag&ViewData?
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
ViewData requires typecasting for complex data type and check for null values to avoid error.
ViewBag doesn't require typecasting for complex data type.

Calling of ViewBag is:
ViewBag.Name = "Vikash";

Calling of ViewData is :
ViewData["Name"] = " Vikash ";

  1. Explain RenderSection in MVC?
RenderSection() is a method of the WebPageBase class. Scott wrote at one point, The first parameter to the "RenderSection()" helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional, and allows us to define whether the section we are rendering is required or not. If a section is "required", then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (that can make it easier to track down content errors). It returns the HTML content to render.
<div id="body"> 

    @RenderSection("featured", required: false) 

    <section class="content-wrapper main-content clear-fix"> 

        @RenderBody() 

    </section> 

</div> 

  1. What is GET and POST Actions Types?
GET
GET is used to request data from a specified resource. With all the 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 which is compulsory and the data, however it can take the following overloads.
.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )


  1. What is display mode in MVC?
Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices and display mode will handle the rest.
For example we can create a view “Home.aspx” which will render for the desktop computers and Home.Mobile.aspx for mobile devices. Now when an end user sends a request to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

  1. How can we do exception handling in MVC?
In the controller you can override the “OnException” event and set the “Result” to the view name which you want to invoke when error occurs. In the below code you can see we have set the “Result” to a view named as “Error”.
We have also set the exception so that it can be displayed inside the view.

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 the above error in view we can use the below code
@Model.Exception;

  1. What is the use of remote validation in MVC?
Remote validation is the process where we validate specific data posting data to a server without posting the entire form data to the server. Let's see an actual scenario, in one of my projects I had a requirement to validate an email address, whether it already exists in the database. Remote validation was useful for that; without posting all the data we can validate only the email address supplied by the user.
Let's create a MVC project and name it accordingly, for me its “TestingRemoteValidation”. Once the project is created let's create a model named UserModel that will look like:
public class UserModel  

{ 

    [Required] 

    public string UserName  

    { 

        get; 

        set; 

    } 

    [Remote("CheckExistingEmail", "Home", ErrorMessage = "Email already exists!")] 

    public string UserEmailAddress 

    { 

        get; 

        set; 

    } 

} 


Let's get some understanding of the remote attribute used, so the very first parameter “CheckExistingEmail” is the the name of the action. The second parameter “Home” is referred to as controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action of the “Home” controller is called and the third parameter is the error message. Let's implement the “CheckExistingEmail” action result in our home controller. 
public ActionResult CheckExistingEmail(string UserEmailAddress) 

{ 

    bool ifEmailExist = false; 

    try 

    { 

        ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmail.com") ? true : false; 

        return Json(!ifEmailExist, JsonRequestBehavior.AllowGet); 

    } catch (Exception ex) 

    { 

        return Json(false, JsonRequestBehavior.AllowGet); 

    } 

} 

  1. Explain Dependency Resolution?
Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.

  1. Explain Bundle.Config in MVC4?
"BundleConfig.cs" in MVC4 is used to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like - jquery.validate, Modernizr, and default CSS references.

  1. What is the meaning of Unobtrusive JavaScript?
This is a general term that conveys a general philosophy, similar to the term REST (Representational State Transfer). Unobtrusive JavaScript doesn't intermix JavaScript code in your page markup.
Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.

Post a Comment

0 Comments