ASP.NET MVC(ASP.NET stands for Active Server Pages in .NET framework and MVC stands for Model-View-Controller) is the framework that is more in demand for developing mobile and web applications. .NET MVC Framework provides a group of class libraries that helps you for developing highly scalable, high performance, and testable applications. MVC is a software design pattern introduced in the year 1970. The MVC pattern will specify that the user should separate their code in such a way that the controller logic, data model, and user interface(view) are decoupled. This implies that it becomes simpler and easier to do maintenance and testing of an application.
Application developers in ASP.NET are high in demand now because companies look onto obtaining a competitive advantage using better custom software programming.
ASP.NET MVC is a lightweight framework for developing web and mobile applications. This framework divides an application into the three main components that make up MVC(Model, View, and Controller). In this MVC pattern for websites, action performance or data retrieval will be done when requests will be sent to a Controller that is in co-ordinance with the Model for doing such tasks. The model will retrieve the data and also store it in the database. The Controller selects the View for displaying and provides it along with the Model. The final page will be rendered by the View-based on the data present in the Model.
MVC along with ASP.NET will give you a powerful and patterns-based way of developing dynamic websites as it enables a separation of concerns.
The 3 main components of an ASP.NET MVC application are model, view, and controller.
In the below-given figure, you can see three main components of the MVC architecture in ASP.NET and interaction among them.
The ASP.NET MVC 5 framework is the newest evolution of the ASP.NET web platform by Microsoft. A highly effective programming model will be provided by ASP.MVC 5, which promotes powerful extensibility, cleaner code architecture, test-driven development, in addition to all the ASP.NET benefits.
Routing in ASP.NET MVC is a pattern matching system that maps the incoming requests from the browser to specified actions of the MVC controller. When the application of ASP.NET MVC gets started, it registers one or multiple patterns with the framework route table so that it can inform the routing engine that what has to be done with the requests that are matching with those patterns. When a request is received by the routing engine during runtime, it matches that URL of the request against its registered URL patterns and provides the response based on a pattern match.
The URL pattern in routing will be considered based on the domain name part in the URL. For example, the URL pattern "{controller}/{action}/{id}"
will look similar to localhost:1234/{controller}/{action}/{id}
. Anything that comes after the "localhost:1234/"
will be considered as the name of the controller. In the same manner, anything that comes after the controller name will be considered as the name of the action and then comes the id parameter value.
If the URL has nothing after the domain name, then the request will be handled by the default controller and action method. For example, the url http://localhost:1234
will be handled by the Index() method and by the HomeController as per the default parameter configuration.
The below-given route table will show which Controllers, Action methods, and Id parameters will be handling the various URLs according to the above-provided default route.
The below figure shows request processing by routing engine and response sent by it. The routing engine provides a response based on URL match in the route table. When the URL of the request matches any of the route patterns that are registered in the route table then the request will be forwarded by the routing engine to the suitable handler for that request. Later the route will be processed and obtain a view on the UI. When the URL of the request doesn't match with any of the route patterns that are registered, the routing engine will indicate that it can't determine how to do request handling by returning an HTTP status code 404.
By using attribute routing, you can easily define some of the URI patterns that are most common in RESTful APIs. For example, resources will usually have child resources such as movies have actors, Clients will have orders, books have authors, etc. So it's obvious to create URIs that reflect these kinds of relations such as /clients/1/orders
. It is difficult to create these kinds of URIs using convention-based routing. With the help of attribute routing, it becomes easier for defining a route to this URI. You need to add an attribute to the controller action as given below:
[Route("clients/{cId}/orders")]
public IEnumerable<Order> ObtainOrdersByClient(int cId)
{
//Statements
}
To enable attribute routing in ASP.NET MVC 5 application, you need to add a call to the method routes.MapMvcAttributeRoutes()
within the RegisterRoutes()
method of RouteConfig.cs
file.
The action methods in ASP.NET MVC will help for executing the request and generating a response to it. Every public method of the MVC Controller is considered an action method. If you want the public method to act as a non-action method, then it is possible to decorate the action method by using the attribute “NonAction”. This will restrict an action method from rendering on the browser.
A few points to be remembered while working with action methods are:
It is possible to create action methods that will return an object of any type like an integer, a Boolean value, or a string. These return types will be wrapped in an ActionResult type that is appropriate before they are being rendered onto the response stream. Any return type that is not an action result will be converted into a string by the ASP.NET MVC and the string will be rendered into the browser. We can create a simple controller as per the code given below:
public class HomeController : Controller
{
public ActionResult HelloInterviewbit()
{
ViewData["SayInterviewbit"] = "Interviewbit";
return View();
}
public string SayInterviewbit()
{
return "This is from 'SayInterviewbit'.";
}
}
We must create a view for running SayInterviewbit() as it will return the View as views\home\SayInterviewbit.cshtml
. For executing the second action method, it does not require the creation of a view. In the browser, the string will be rendered. It is possible for an void public method to act as an action method. This implies that any public method can become an action method.
The area will permit to divide the larger application into smaller units where every unit will have an MVC folder structure separately, exactly like the default MVC folder structure. Consider an example of a large enterprise application that might have different modules such as HR, finance, admin, marketing, etc. So for all these modules, an Area can have a separate MVC folder structure.
Action methods on controllers will return JsonResult that will be used within an AJAX application. From the "ActionResult" abstract class, this JsonResult class will be inherited. Here Json will be supplied with a single argument that must be serializable. The JSONResult object will serialize the specified object into JSON format.
Example:
public JsonResult JsonResultExample()
{
return Json("Hello InterviewBit!!");
}
The five types of Filters in ASP.NET MVC and order of their execution are as follows:
IAuthenticationFilter
.IAuthorizationFilterinterface
. Examples of an Authorization filter are:IActionFilter
in the framework, which has OnActionExecuting and OnActionExecuted methods. OnActionExecuting method executes before the Action and provides an opportunity for Action call canceling. Since action filters are executed before and after a controller action executes, they can also be used for modifying the view data that is returned by a controller action.IResultFilter
interface in the framework, which has two methods namely OnResultExecuting and OnResultExecuted. An example of a result Filter is OutputCacheAttribute class which will provide output caching.IExceptionFilter
interface in the framework. It is very helpful during the execution pipeline where any unhandled exceptions might be thrown. An example for ExceptionFilter is HandleErrorAttribute class which will specify the way for handling an exception thrown by an action method.It is possible to override the methods in your controller class if you wish to do so.
Action filters are the additional attributes in the ASP.NET MVC framework, that we can apply to either a section of the controller or to the entire controller for modifying the approach in which action will be executed. Action filter attributes are said to be special .NET classes as they are derived from the System.Attribute
class and they can be attached to classes, properties, methods, and fields.
The following action filters are provided by ASP.NET MVC:
The below-given code will apply Output cache filter on an ActionFilterExampleController (Here, ActionFilterExampleController is just used as an example, You can apply action filters on any of the controllers). It specifies that the return value should be cached for 20 seconds.
public class ActionFilterExampleController: Controller
{
[HttpGet]
OutputCache(Duration = 20)]
public string Index()
{
return DateTime.Now.ToString("T");
}
}
There are several advantages of ASP.NET MVC. Few are:
ViewBag:
public class ExampleController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "This is about ViewBag ASP.NET MVC!!";
return View();
}
}
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>IndexDisplay</title>
</head>
<body>
<div>
@ViewBag.Message
</div>
</body>
</html>
ViewData:
ViewDataDictionary
and is originally a Dictionary object, which means it has Keys and Values where Keys represents the String and Values will be objects. Data will be stored in the form of Objects in ViewData.public class ExampleController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "This is about ViewData in ASP.NET MVC!!!";
return View();
}
}
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div>
@ViewData["Message"]
</div>
</body>
</html>
Bundling and minification are two techniques used for your web application in the ASP.NET MVC framework for improving the performance of the page load. Bundling will combine several files into a single file. Minification will perform different types of code optimizations to CSS and scripts, which will result in smaller payloads. With the help of bundling and minification, we can improve the performance of load time by reducing the requested assets(like JavaScript and CSS files) size and by reducing the number of requests to the server.
A View Engine is an MVC subsystem and has its own markup syntax. It will convert the template from server-side into HTML markup and then render it to the browser. In the beginning, ASP.NET MVC was having a single view engine i.e., web forms(ASPX), from ASP.NET MVC 3 a Razor view engine Razor has been introduced. You can also make use of other view engines such as NHaml, Spark, etc., in ASP.NET MVC.
Razor View Engine in ASP.NET MVC is a simple-syntax view engine used for creating a view of an application. It was released in January 2011 for Microsoft Visual Studio as a part of ASP.NET MVC 3.
Razor will make use of C# syntax for the purpose of embedding code in a page without the usage of ASP.NET delimiters: <%= %>
. The file extension of Razor is "cshtml" for the C# programming language. It supports Test Driven Development(TDD)) as it will not be dependent on the System.Web.UI.Page
class.
TempData is a dictionary object useful for the temporary storage of data. It is an instance of the Controller base class. It is useful in storing the data for the duration of an HTTP request, or we can say that it can store live data between two consecutive requests of HTTP. It is also useful in passing the state between action methods. TempData can be used only with the subsequent and current requests. It will make use of a session variable for storing the data. TempData needs typecasting during data retrieval.
Example: In the below-given code, employee details will be temporarily stored by TempData.
public ActionResult FirstRequest()
{
List<string> TempDataDemo = new List<string>();
TempDataDemo.Add("Harish");
TempDataDemo.Add("Nagesh");
TempDataDemo.Add("Rakshith");
TempData["EmployeeName"] = TempDataDemo;
return View();
}
public ActionResult ConsecutiveRequest()
{
List<string> modelData = TempData["EmployeeName"] as List<string> ;
TempData.Keep();
return View(modelData);
}
TDD or Test Driven Development is an approach where a test will be written before the completion of production code writing for the purpose of refactoring and fulfilling the test. TDD is also known as the Red-Green-Refactor method of development.
The Workflow of TDD is given below:
The collection of input values(example: city, mobile number, e-mail id, etc.) of a specific web page is called as state of that page. By default, it is not possible to retain the values(states) provided on a single page of a web application, when you navigate to another web page. This nature of a web page is known as stateless behavior.
You can make use of different state management techniques for retaining the values(state) across the web pages. The below-given common state management techniques will be supported by the ASP.NET MVC:
Authentication means providing access to the user for a particular service through verification of his/her identity using his/her credentials such as email-id and password or username and password. It will make sure that the correct user will be authenticated or logged in for a particular service and the right service will be given to the specific user depending on their role.
Forms authentication in ASP.NET will be done after the completion of IIS(Internet Information Services) authentication. It is possible to configure forms authentication with the help of the forms element in the file web.config
of your application. The forms authentication default attribute values are given below:
<system.web>
<authenticationmode="Forms">
<formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" />
</authentication>
</system.web>
The FormsAuthentication class will automatically create the authentication cookie when it calls the methods RedirectFromLoginPage()
or SetAuthCookie()
. The value of an authentication cookie will be having the string representation for the signed and encrypted FormsAuthenticationTicket object.
Scaffolding is a code generation framework used for ASP.NET web applications that will be helpful in effectively generating the code for CRUD(Create, Read, Update, and Delete) operations against your database.
The advantages of Scaffolding are as follows:
A life cycle refers to a sequence of events or steps used for handling some kind of request or modifying the state of an application.
ASP.NET MVC has two life cycles. They are:
The application life cycle: The ASP.NET application life cycle begins when a request is raised by a user. It refers to the time when the application process starts running IIS(Internet Information Services) till the time it ends. This is identified as the start and end events of an application in the startup file of your application.
On Application Start, the application_start() method will be executed by the webserver. All global variables will be set to default values using this method. On the Application End, the application_end() method will be executed and this will be the final part of the application. The application will be unloaded from the memory in this part.
The Request Life Cycle: It refers to the series of events that will be executed each time when an HTTP request has been handled by the application.
Routing is considered to be an entry point for each MVC application. After the request is received by the ASP.NET platform, it finds out how the request has to be handled with the help of the URL Routing Module. Modules are the components of a .NET that can be attached to the application life cycle. The routing module is helpful in matching the incoming URL(Uniform Resource Locator) to the routes that are defined in our application. All routes will be having a route handler associated with them and this route handler is considered to be an entry point to the MVC framework.
The route data will be converted by the MVC framework into a concrete controller that is capable of handling the requests. The major task after the creation of a controller is Action Execution. An action invoker component will find and select the suitable Action method for invoking the controller.
The next stage after the preparation of the action result is Result Execution. MVC will separate result declaration from result execution. If the result is of view, then it will find and render our view by calling the View Engine. If the result is not a view type, the action result will be executed on its own. This Result Execution will generate an original response to the actual HTTP request.
The RenderSection() method belongs to the WebPageBase class and is used for rendering the content of the defined section. The RenderSection() method's first parameter will be the section name we wish to render at that particular location in the layout template. The second parameter will enable us for defining whether the rendering section is needed or not and this parameter is optional. If it is a "required" section, then an error will be thrown by the Razor if that section has not been implemented within a view template. It returns the HTML content for rendering purposes.
For example, a section named "note" in a layout page can be defined as follows:
@section note{
<h1>Header Content</h1>
}
The above-defined section can be rendered on the content page by using the below code:
@RenderSection("note")
All sections are compulsory by default. To make the sections optional, you need to provide the value of the second parameter as a boolean value false.
<div id="body">
@RenderSection("note", false) //used for injecting the content in the defined section
<section class="content-wrapper main-content clear-fix">
@RenderBody()
</section>
</div>
Using the above code, the section named "note" will be rendered on the content page. Here, the RenderBody method can be used for rendering the child page/view.
Helper methods are useful in rendering the HTML in the view. These methods will generate an HTML output as a part of the view. They need less coding as it can be reused across the views, so it is advantageous over HTML elements. The different built-in helper methods are available that can be used for generating the HTML for a few most commonly used HTML elements such as dropdown list, form, checkbox, etc. Along with this, it is also possible to create our own helper methods for custom HTML generation.
A few standard helper methods in MVC are given-below:
@Html.ValidationSummary(True, "Please fix the problem:")
Glimpse is a web debugging and diagnostics tool that can be used with your ASP.NET or ASP.NET MVC applications for finding the information related to performance, debugging, and diagnostic. It helps you to obtain information regarding model binding, timelines, environment, routes, etc. It is possible to integrate Glimpse with insights into an application.
An intuitive user interface will be provided by Glimpse for examining the performance data of an application. Glimpse adds a widget to the web pages for viewing the performance-related data as you browse through the application web pages.
ASP.NET MVC will permit only a single model to be bound to each view, but there are many workarounds for this. For example, the class ExpandoObject in the ASP.NET framework is a dynamic model which will be passed to a view.
Another common solution is the usage of ViewModel class(a class with several models), ViewBag(a property of the ControllerBase class which is dynamic), or ViewData(a dictionary object). It is also possible to use Tuple, JSON, and RenderAction.
In the example given below, you can get to know about how to use multiple models in a single view with the help of the ViewModel class. In this example, ViewModel has two properties namely Managers and Employees that acts as a model.
ViewModel class:
public class ViewModel
{
public IEnumerable<Manager> Managers { get; set; }
public IEnumerable<Employee> Employees { get; set; }
}
Controller code:
public ActionResult IndexViewModel()
{
ViewBag.Message = "Welcome to my example program!";
ViewModel demomodel = new ViewModel();
demomodel.Managers = GetManagers();
demomodel.Employees = GetEmployees();
return View(demomodel);
}
View code:
@using MultipleModelInOneView;
@model ViewModel
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p><b>Manager List</b></p>
<table>
<tr>
<th>ManagerId</th>
<th>Department</th>
<th>Name</th>
</tr>
@foreach (Manager manager in Model.Managers)
{
<tr>
<td>@manager.ManagerId</td>
<td>@manager.Department</td>
<td>@manager.Name</td>
</tr>
}
</table>
<p><b>Employee List</b></p>
<table>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Designation</th>
</tr>
@foreach (Employee employee in Model.Employees)
{
<tr>
<td>@employee.EmployeeId</td>
<td>@employee.Name</td>
<td>@employee.Designation</td>
</tr>
}
</table>
Few significant namespaces that are used in ASP.NET MVC applications are:
beforeFilter(): This function will be executed before each action in the controller. It will inspect user permissions or check for an active session.
beforeRender(): This function will be executed before the rendering of the view and immediately after controller action logic. This function will not be frequently used, but it might be needed if you manually call the render() function before the end of a given action.
afterFilter(): This function will be called after each controller action, and also after the completion of rendering. It is the last method in the controller to run.
Three different development approaches will be provided by the Entity framework while dealing with the database and data access layer in the application according to the need of the project. They are:
Database-First Approach: This approach will be used if there is an already existing database schema. Here, context and entities will be generated for the existing database using the EDM(Entity Data Model) wizard. This approach is considered to be the best for applications that will make use of an already existing database.
The Database-First approach is useful in the following cases:
Code-First Approach: This approach is used when the existing database is not present for your application. In this approach, you will write the entities(domain classes) and context classes, then the database will be created from these classes with the help of migration commands.
This approach is considered to be the best for highly domain-centric applications and that will create the domain model classes in the beginning. Here, the database will be required only as a persistence mechanism for these newly created domain models. That implies, if a developer is following the principles of Domain-Driven Design(DDD), they will start the coding with the creation of domain classes and then the database required will be generated for persisting their data.
The Code First approach is useful in the following situations:
Model-First Approach: In this approach, the entities, inheritance hierarchies, and relationships will be created directly on the visual designer and then can generate context class, database script, and entities using the visual model.
The Model-First approach is useful in the situation:
A postback will occur when clients make a request for a server response from their viewing page. Consider a simple example of a form completion by the user and hitting the “submit” button. In this case, the property IsPostBack will be true, so the request will be processed by the server and a response will be sent back to the client.
A postback helps to refresh the entire page when a data retrieval request has been made with a callback without completely refreshing the page.
[Authorize]
public class LibraryControllerDemo:Controller
{
[Allowanonymous]
public actionresult obtainBook()
{
return view();
}
[Authorize("AdminLibrary")]
public actionresult modifyBook()
{
return view();
}
}
[Allowanonymous]
- It will allow all users to access the obtainBook() method.
[Authorize("AdminLibrary")]
- It will restrict the AdminLibrary user from accessing the modifyBook() method.
There are many ways to achieve the result for this scenario. Two of the methods among them are as given below:
Option 1:
The ChildActionMethod will permit you for restricting access to action methods that you don't want users to directly request in the URL of the browser.
[ChildActionOnly]
public ActionResult demoPiper()
{
return View();
}
Now, the demoPiper() action method cannot be directly requested by the user through the URL of the browser.
Option 2:
In ASP.NET MVC, each controller's method is accessed through a URL, and in case you don't want an action created by you to be accessible through URL then you need to protect your action method with the help of the NonAction attribute provided by the MVC.
[NonAction]
public ActionResult demoPiper()
{
return "demoPiper.com";
}
After the demoPiper() method is declared as NonAction, if you try to access the method or action through URL, then HTTP 404 Not Found error will be returned.
It is possible to overload the action methods by passing the name of the method in the ActionName attribute as given below:
[ActionName("ActionMethodExample")]
public ActionResult getInfo(int id)
{
return "";
}
Another action method with the same name can be declared as given below:
public ActionResult getInfo()
{
return "";
}
Now, these two getInfo()
methods can be overloaded as they are having the same function name but differ in the number of arguments.
The HandleError attribute is used to manage the unhandled exceptions in the action method of the ASP.NET MVC application. Consider that the HandleError is not used in the application, and in case an unhandled exception is thrown by an action method then the default error page with sensitive information will be displayed to everybody.
It requires enabling of custom errors in the web.config
file, before the usage of HandleError.
<system.web>
<customErrors mode="On" defaultRedirect="Error" />
</system.web>
Few properties of HandleError can be used for handling the exception. They are:
The following steps will explain how to create an ASP.NET MVC-based web application using Visual Studio 2019 IDE.
Creating a Web Project:
Open the Visual Studio and click on the menu bar, then select the new option for creating a new project. You can see how to create a new project in the below-given image:
Select Project Type:
Select the project type as an ASP.NET Web Application(.NET framework) and click on the Next button.
Provide Project Name:
The name of the project should be provided in the following window and then click on Create button.
Select MVC template:
Now, select the MVC web template from the list of templates available, as we are implementing the MVC project. Then click on Create.
MVC Web Application Project Structure:
The following image represents the project structure of the project created by us.
You can see that the Project structure is having three folders namely Model, View, and Controller. The default controller for the created application is the HomeController. By default, the HomeController consists of the following code:
// HomeController.vb
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Return View()
End Function
Function About() As ActionResult
ViewData("Message") = "Your application description page."
Return View()
End Function
Function Contact() As ActionResult
ViewData("Message") = "Your contact page."
Return View()
End Function
End Class
The Index file in the views folder will be the default file for the home controller.
// index.vbhtml
@Code
ViewData("Title") = "Home Page"
End Code
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div>
The above default code in the project will produce the below-given output when it is viewed in the browser:
The MVC pattern of ASP.NET has various advantages because of the separation between business logic, input logic, and user interface(UI) logic. But it has a few drawbacks such as it is completely controlled by JavaScript, HTML, and CSS, also it cannot be easily learned without any experiments.
If anyone wants to be a .Net MVC expert developer, you must join MVC training to learn commonly used C# programming language, SQL Server, OOPs, and some of the front-end technologies such as JavaScript, HTML, JQuery, etc.
This article includes a list of interview questions on ASP.NET MVC. To become a become industry competent, apart from learning the ASP.NET MVC, read this article to crack your job interview. All the Best..!!
System.Web.Mvc.WebFormViewEngine
System.Web.Razor
System.Web.Mvc.WebFormViewEngine
_Layout.cshtml
_ViewStart.cshtml
_Login.cshtml
_ViewStart.cshtml
AuthConfig.cs
in ASP.NET MVC?RouteConfig.cs
in ASP.NET MVC?