MVC Interview Questions

Want to become an expert in cracking ASP.NET (Core) MVC interview questions? Start with practising the questions below. Crack your next MVC interview with the frequently asked questions.

  • 4.8 Rating
  • 20 Question(s)
  • 25 Mins of Read
  • 9711 Reader(s)

Beginner

MVC architecture represents the domain-specific data and business logic. It maintains the data of the application, model data hold the data in public property.

We can also manipulate the data in the business logic layer

Namespace mvc.Models
{
   public class Student
{
   public int StudentId { get; set; }
   public string StudentName { get; set; }
   public int Age { get; set; }
}
}

In Model, we can apply validation to the property using Data Annotation instead of applying on the client side. For adding data Annotation we need to add the reference “System.ComponentModel.DataAnnotations assembly”

Like we apply on StudentId

Eg. 

[Display(Name=”StudentId ”)]
[Required(ErrorMessage=”StudentId is Required”)]
Public int StudenId {get;set;}

View View is the User Interface where The user can display its own data and can modify its data, In this, the data is passed from the model to the view. The view has a different folder with the same name as of controller and has different views in it of different actions.

There are 3 types of Views in MVC

  • User View : To create this view use page template. The inherited class name will be available in <%@ page directive with inherits attributes.
  • Master Page View : To create a master page view we use a template known as “MVC2 view master page.it have a default extension of.master.
  • Partial View : Partial View is the same as UserController in asp.net it is inherited from the System.Web.Mvc

Controller: It is the most essential part of the MVC in asp.net since it is the first recipient which interacts with HTTP and finds the model and actions. So it is the controller which decides which model should be selected and how to carry the data from the respective view, a controller is inherited from the System.Mvc.Controller. The routing map of the controller is decided in RouteConfig.cs which is under App Start Folder.

Eg, http://localhost:61465/Employee/Mark

Where Employee is a controller name and mark is the action.

The advantages of MVC of ASP.NET are :

  1. It provides a separation feature where one developer can work on Controller and the other can work on View to create the business logic layers of the web application. This results that the MVC model is much faster than the other programming patterns.
  2. The Duplication of code is very limited in MVC because it separates data and business logic from the display by creating multiple views for a model.
  3. It can work with a javascript framework which makes it work with the Pdf files and other widgets. Its asynchronous techniques help the developer to develop and load the application faster.
  4. It is very helpful when we want some frequent changes in the web application like changing colours, fonts, screen layouts, and adding new device support for mobile phones or tablets.it is very simple to add views since adding views not affect on the model, so changing in models does not affect the architecture of the web application.
  5. MVC web applications are very useful to develop the SEO platform. This method of development of architecture is commonly used in the Test Driven Development applications. Moreover, Scripting languages like JavaScript and jQuery can be integrated with MVC to develop feature-rich web applications. Projects that are developed with the help of MVC model can be easily developed with lesser expenditure and within less time too. As a result, today organizations are looking for development of web applications based on MVC architecture for cost and time benefits. There are many companies who provide MVC development services to develop web applications that satisfy every requirement of the clients.

Razor is not a programming language but an HTML markup language which is written on the server side using C#. Razor does not have the tie-up with Asp.net mvc. It has implemented a view engine to use razor view to produce the HTML output. It uses the @{....} syntax. It uses a semicolon to end the statement, it has .cshtml as file extensions.inline expression also uses the @ expression’

Conditions with if statement

It starts with a code block and its condition is written in parenthesis.  the code which needs to be executed is written inside braces.

@{var Price=60;}
<html>
<body>
<if(Price>60)
{
<p>This is paragraph</p>
}
</body>
</html>

In the above example, we have declared var price has a value of 60 and we are using if statement which is validating price. the code written in side braces gets executed,if price value is greater than 50.

In razor, we have a different type of block statements available, which are

1.Single Statement Block and Inline Expression: It is the same as we discussed above that it is the block of code which is executed in the single line statement.

          @{var series=4;}
<p>MVC series :@series</p>
<p>Razor Message:@RazorMessage</p>

2.Multiple Statement Block with Inline Expressions : In this we declare all the variable in single @{....} and each variable is ended with the semi colon

@{
            Var a =”This is Razor Syntax”;
            Var b = DateTime.Now.DayOfWeek;
            Var c = a + “Date on ”+b;
}
<p>Razor Message:@HomeMessage</p>

So it is better to declare the variable at the top of the view because if we declare the variable at the top then it can be used in all inline block of statement written on that view and if we declare this variable at the middle order of view then we cannot use at the top statement written in @{....}.

When a programmer send the request and when it goes to the action method it sees the return type of  the action result and produces the desired result on the view after that,

Action Result is a result of action methods or return types of action methods. Action result is an abstract class.

Different types of ActionResult are-

  1. View Result
  2. Partial View Result
  3. Redirect Result
  4. Redirect To Action Result
  5. Redirect To Route Result
  6. Json Result
  7. File Result
  8. Content Result

1.View Result: View Result is very simple Action Result type it is a class which is derived from the ViewResultBase class and viewResultBase Class is derived from the ActionResult, View results in the data in view which is defined in the model. View page is a simple HTML page. Here view page has “.cshtml” extension

         Eg,

 Public ViewResult About()
{
ViewBag.Message=”The View Result is here”;
Return View();
}

2.Partial View Result : The partial view is a class which is also derived from action result class. When we create a partial view it is created in the shared folder with the .cshtml extensions. If we don't have the partial view we cannot access the partial view, Partial view is one of the views that we can call inside the Normal view page.

Eg. 

public partialViewResult Index()
{
Return PartialView(“_PartialView”);
}

3.Render Result: it helps in redirecting the request to the specific url ,if the url is wrong then it gives the Error 404

Eg  

public RedirectResult Index()  
{  
return Redirect("Home/Contact");  
}

4.Redirect to Action Result: it helps in redirecting the request to action through the controller it is not necessary to mention the controller name in RedirectToAction() if controller is not there then it will redirected to the action which matches in RedirectToAction() ,if action does not find on the page then it will give the error 404.

public ActionResult Index()  
{  
return RedirectToAction("Login", "Account");  
}

5.Json Result : Json result is a significant Action Result in MVC. It will return response in the format of key value pairs.it return json if we call json method

Eg:

 Public ActionResult Index()   
{  
var persons = new List<Person1>  
 {  
new Person1
{
Id=1, FirstName="Harry", LastName="Potter"
},      
new Person1
{
Id=2, FirstName="James", LastName="Raj"
}   
};   
return Json(persons, JsonRequestBehavior.AllowGet);
 }

ViewData:ViewData is used when we want to transfer the data from controller to view it as a dictionary which is used to transfer the data in the form of key-value pair where key is always string, we can transfer the data from the controller to view but it is not possible to transfer the data from view to controller using ViewData.

Eg, 

ActionResult Index()
{
IList<Student> studentList = new List<Student>();
studentList.Add(new Student(){ StudentName = "Bill" });
studentList.Add(new Student(){ StudentName = "Steve" });
studentList.Add(new Student(){ StudentName = "Ram" });
ViewData["students"] = studentList;
return View();
}

Access ViewData in a Razor View

<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{ <li> @std.StudentName </li>
}
</ul>

Add KeyValuePair in ViewData

public ActionResult Index()
{
ViewData.Add("Id", 1);
ViewData.Add(new KeyValuePair<string, object>("Name", "Bill")); ViewData.Add(new KeyValuePair<string, object>("Age", 20));
return View();
}

Viewdata request is last till the current web request, it the cleared the view data when there is the redirection, before using the viewdata we need to cast it. We can use the temp data in MVC 1.0 and its above version.it requires the type conversion while we are enumerating. It will throw the error when there is the redirection of a request.

ViewBag : ViewBag is used to when we want to transfer the small amount of data from Controller to view or we can say when we want to transfer temporary data (which is not included in model) from the controller to the view.its derived from the controller base Class which is a base class for all the controller,it attaches the name property with dot notation and assign the string value in it and using razor syntax @ to get the server side code,

You can assign any number of properties and values to ViewBag. What so ever time you will assign the values to the viewbag it will consider the last value defined in the property.

namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
IList<Student> studentList = new List<Student>()
{
new Student()
{
StudentID=1, StudentName="Steve", Age = 21
},
new Student()
{
StudentID=2, StudentName="Bill", Age = 25
},
new Student()
{
StudentID=3, StudentName="Ram", Age = 20
},
new Student()
{
StudentID=4, StudentName="Ron", Age = 31
},
new Student()
{
StudentID=5, StudentName="Rob", Age = 19
}
}; // GET: Student
public ActionResult Index()
{
ViewBag.TotalStudents = studentList.Count();
return View();
}
}
}

On view page we can access the data by

<label>Total Students:</label> @ViewBag.TotalStudents

TempData: ASP.NET MVC can be used to store temporary data which can be used in the subsequent request.it is very useful when we want to transfer the data from one action to another action or from one controller to another controller, the data is passed in the form of key-value pair

public class HomeController : Controller

{ // GET: Student
public HomeController()
{
}
public ActionResult Index()
{
TempData["name"] = "Test data";
TempData["age"] = 30;
return View();
}
public ActionResult About()
{
string userName;
int userAge;
if(TempData.ContainsKey("name"))
userName=TempData["name"].ToString(); if(TempData.ContainsKey("age"))
userAge = int.Parse(TempData["age"].ToString());
return View();
}
}

Life span for temp data is very small. Data in TempData can persist only upto next view or upto next controller action. If we want to take data in TempData to successive requests then we need to call a method: TempData.Keep(), to keep the data persists for next request.

Advanced

Unobtrusive javascript library allows to add validation to MVC views without any additional coding, only required to use attributes like RequiredAttribute, RangeAttribute and include the correct script files.

Example:

public class AddUserVM
{
   [DisplayName("First Name:")]
   [Required(ErrorMessage = "Please enter the first name.")]
   public string FirstName { get; set; }
   [DisplayName("Last Name:")]
   [Required(ErrorMessage = "Please enter the last name.")]
   public string LastName { get; set; }
   [DisplayName("Age:")]
   [Range(12, 120, ErrorMessage = "You must be between 12 and 120 years of age.")]
   public int Age { get; set; }
   [DisplayName("Email:")]
   [Required(ErrorMessage = "Please enter an email address.")]
   [EmailAddress(ErrorMessage = "Please enter a valid email address.")]
   public string EmailAddress { get; set; }
}

The above class setup is to handle the server side validations. Unobtrusive validations allow us to take existing validation attributes and use them at client-side to make the user experience much better.

Routing enables us to define a URL pattern that maps to the request handler.in asp.net request handler is .aspx file while in MVC request handler is controller and actions. All the route of the application is stored in RouteTable and the Routing engine helps in finding the appropriate handler class for the request, when the request and goes to the route table if it finds the appropriate  actions and controller and give the response and if it doesn`t find the controller and actions it will give the Error 404.

When we create the MVC application it creates one route by default which is defined under RouteConfig.cs file under AppStart Folder

Eg- public class RouteConfig

{
    Public static void RegisterRoutes(RouteCollection Routes)
{
routes,MapRoutes(name:”Deafult”,”
url : “{controller}/{actions}/{id}”,
deafults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional});
}
}

As we have seen in above that in Maproute() extension method of the route collection, where the name is default, URL pattern is “{controller}/{action}/{id}Defaults specify which controller, action method or value of id parameter should be used if not present in the incoming request URL. the main content of the URL is after the domain name localhost:1234/{controller}/{action}/{id}.

Where localhost:1234 is the domain name, if the URL doesn't contain anything after the domain then the default request i.e Home as  a controller and the Index as a view will handle the request

We can also configure a custom route using MapRoute extension method. We need to provide at least two parameters in MapRoute, route name, and a URL pattern. The Defaults parameter is optional.

Eg- public class RouteConfig

{
    Public static void RegisterRoutes(RouteCollection Routes)
{
routes,Map Routes(
name:”Default”,
url:”{controller}/{actions}/{id}”,
defaults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional});
routes,Map Routes(
name:”Students”,
url:”Students/{id}”,
defaults:new {controller=”Students”,action=”Index”l});
}
}

In the above example, there is a custom route where controller name is Students and since there is no such action defined in the URL so the default action is an index for all the actions belongs to the controller class.

When we want to be executed just prior to the action execution, when the user sends the request to the controller, in this the user create the custom class which works as a filter where the developer writes the logic which will be implemented just prior to the action execution, By programming method we can apply filters to the actions ,There are different type of filter use in MVC :

  1. Authorization: Authorization and authentication before executing the actions of the controller. built-in filter used is [Authorize], [RequireHttps], interface used is IAuthorizationFilter.
  2. Action Filters: it performs some action before and after the action methods execute before and after executing the action in the controller, there is no built-in filter used in this and interface used is IActionfilter.
  3. Result Filter: it basically performance some operation after and before the execution of view result. The build is filter used is [OutputCache].the interface used is IResultFilter.
  4. Exception filters: Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. The built used is [HandleError] and the interface used is IExceptionFilter.

When there is any kind of exception in an application then the exception filter executes. HandleErrorAttribute ([HandlerError]) class is a built-in exception filter class in MVC framework. The HandleErrorAttribute class renders Error.cshtml which is inside the shared folder which is added by default during project creation when an unhandled exception occurs.

[HandleError]

public class HomeController : Controller
{
public ActionResult Index()
{
throw new Exception("This is unhandled exception");
return View();
}
public ActionResult About()
{ return View();
}
public ActionResult Contact()
{
return View();
}
}

Html helper class helps when we want to show the property of the modal class into the view we use HTML helper class also when we want the values from the HTML input method parameter into the modal property we use HtmlHelper, HtmlHelper class generates HTML elements using the model class object in razor view.

Eg.

<p>
@Html.ActionLink(“Create New”,”Create”)
</p>

@Html is an object of HtmlHelper class. (We can  access a server-side object in razor syntax by using @ symbol).it is a property which is included in the base class of razor view WebViewPage. ActionLink() and DisplayNameFor() is extension methods included in HtmlHelper class, HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper.

“HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post” when the user clicks on the “Save” button.

Html.Beginform is very helpful as it helps us in changing the Url and helps us in changing the methods, The Html.LabelFor HTML Helper creates the labels on the screen. If we entered something wrong then it will display the error using Html.ValidationMessageFor .

There are lots of benefits:

It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.

It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology).

In ASP.NET MVC data Annotation are built in validation which  is applied on the modal class property and render it on the view in the validation summary

The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace

Different types of data annotations are :

  1. Required
  2. String Length
  3. Range
  4. Regular Expression
  5. Credit Card
  6. Custom Validation
  7. Email Address
  8. File Extension
  9. Max Length
  10. Min Length
  11. Phone

Eg. 

public class Student

{
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
[Range(5,50)]
public int Age { get; set; }
}

In the above-stated example, we have the Required data annotation which implies that this field must be required in every scenario if the user left this modal property empty then it will give the default error message. In the same way, we can use the range to find the age property. This will validate and display an error message if the user has either not entered Age or entered an age less than 5 or more than 50.

Eg.

namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
public ActionResult Edit(int id)
{
var std = studentList.Where(s => s.StudentId == StudentId) .FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
if (ModelState.IsValid)
{ //write code to update student return RedirectToAction("Index"); }
return View(std);
}
}
}

In this Modal State will check whether the data is valid is true and it will update in the database and if not then it will return the same data in the Edit View

ModelState.IsValid determines that whether submitted values satisfy all the DataAnnotation validation attributes applied to model properties.

Eg  In the View the Data Annotation for the modal property will look like this

<div class="form-group">
@Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
</div>
</div>

The validation Summary helper method will display the error message, ValidationMessageFor is responsible to display an error message for the specified field.

Html.RenderPartial is directly written to the HTTP response stream which is used the same Text Writer object as used in the current webpage/template. Since there is no return type of Validation Annotations in MVC, the return type of Validation Annotations is void. We don't need to create any actions so it is simple to use, it is very useful when we want to show the data which is in another model view.

For example: if we want to show comments of an article, we will prefer to use RenderPartial method since the information and comments of the article are already populated in the view model.

@{Html.RenderPartial("_Comments");}

When it is executed its result is directly written to the response stream which makes it faster when compared with the partial method

In Html.Partial, the partial view is viewed as an encoded HTML string. Due to its string value return type, we can store the Html.Partial value in a variable.it same as Html.RenderPartial in case of action creation also,  we don’t need to create action, Partial method is also useful when the displaying data in the partial view is already in the corresponding view model which same as html.RenderPartial.

@Html.Partial("_Comments")

when we want a certain code to be used at some other view, we use a partial view. In simple words we can say that  it is a child view which can be used in some other views, it prevents the duplicate of code since it used the same partial view at some other places

When we want a partial view to be used on multiple controllers then we need to create a shared folder in the solution, otherwise, if it using in a single controller then it doesn`t need it. Using Partial() or RenderPartial() or RenderAction() helper method .we can render the partial view content in its parent view

@Html.Partial() helper method renders the specified partial view. It returns HTML string so we have a chance of modifying the HTML before rendering.

The different types of overloads used in partial views are:

  1. MvcHtmlString Html.Partial(string partialViewName)
  2. MvcHtmlString Html.Partial(string partialViewName,object model)
  3. MvcHtmlString Html.Partial(string partialViewName, ViewDataDictionary viewData)
  4. MvcHtmlString Html.Partial(string partialViewName,object model, ViewDataDictionary viewData)

MvcHtmlString Html.Partial(string partialViewName) : it Renders the given partial view content in the referred view.

MvcHtmlString Html.Partial(string partialViewName, object model): in this, the modal passes its parameter into the partial view and render the view which is referred to it.

MvcHtmlString Html.Partial(string partialViewName, ViewDataDictionary viewData): it passes the view data dictionary to the partial view and render the partial view content in the preferred view.

MvcHtmlString Html.Partial(string partialViewName, object model, ViewDataDictionary viewData): when we want to pass the model object and view data dictionary to the partial view, and render the partial view content in the referred view.

when we want to improve the performance of the application we use output caching, it prevents the duplicate content to be loaded by caching the content returned by the controller,  when the controller methods are invoked, it is the best method to reduce the server round trips, reduces database server round trips, reduces network traffic etc.

Let’s Suppose when we want to display the list of records from the database in the view , so every time when the user invokes the controller method the query will be executed which will reduce the performance of the application, So, we can advantage of the "Output Caching" that avoids executing database queries each time the user invokes the controller method.

It is not necessary that the data will be retrieved until the time we have given, When memory resources become low, the cache starts evicting content automatically, and thus increase the performance of the Project.

The duration is in seconds by default the value used is 60 seconds

[HttpPost]  
   [OutputCache(Duration = 10, VaryByParam = "name")]  
   public ActionResult SearchCustomer(string name = "")  
   {
       NorthwindEntities db = new NorthwindEntities();  
       var model = from r in db.Customers  
                   where r.ContactName.Contains(name)  
                   select r;
       if (model.Count() > 0)  
       {
           return View(model);  
       }
       else
       {
           return View();  
       }
   }

In the above code the "name" parameter passed by the user and then, depending on the name, selecting matching records with a LINQ query and then checking if the model has the number of records greater than zero then send the model to the view else simply send the view (no model),VaryByParam="name" and "VeryByParam" is something that makes many differences

1.VaryByParam = "none": Think of it like, we don't want to care about the form parameter or query string parameter passed by the user from the view page. If I use "none" then it will create the same cached version of the content for every user who visits the website,

2.VaryByParam = "name": By using this we can create different cached versions of the content when the query string parameter is varied from one param to other. In other words if I find records matching "ce" string then a new cache will be created by replacing the older one, again if I find records matching "ab" string then a new cache will be created by replacing the last one ("ce" cached), no matter duration is elapsed or not.

Bundling and Modification is used to improve the request load time, In this, we can store many static files from the server in a single request, It is created in BundleConfig.cs in the App_Start folder, This file is creating Bundles by associating multiple files to routes. For example, the "~/bundles/bootstrap" route will correspond to both the bootstrap.js file and the respond.js file, and the browser will only need one HTTP request to retrieve both files

Eg.

using System. Web;
using System.Web.Optimization;

namespace BundlingExample
{
   public class BundleConfig
   {
       public static void RegisterBundles(BundleCollection bundles)
       {
           bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                       "~/Scripts/jquery-{version}.js"));

           bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                       "~/Scripts/modernizr-*"));

           bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                     "~/Scripts/bootstrap.js",
                     "~/Scripts/respond.js"));

           bundles.Add(new StyleBundle("~/Content/css").Include(
                     "~/Content/bootstrap.css",
                     "~/Content/site.css"));

           BundleTable.EnableOptimizations = false;
       }
   }
}

Minification : Minification is used to remove the white space, text, short comments from the files such as JavaScript and CSS files without expecting to alter functionality to reduce the size, which causes improved load times of a Webpage.

Eg.

sayHello = function(name)
{ //this is comment
var msg = "Hello" + name; alert(msg);
}
Minified Javascript is
sayHello=function(n){var t="Hello"+n;alert(t)}

it has removed unnecessary white space, comments and also shortening variable names to reduce the characters which in turn will reduce the size of JavaScript file., It increases the loading effects of a page by minimizing the number of request and size of the files.

There are different types of bundles used in MVC which is defined under the System.web.Optimization namespace

ScriptBundle: ScriptBundle is responsible for JavaScript minification of single or multiple script files.

StyleBundle: StyleBundle is responsible for CSS minification of single or multiple style sheet files.

DynamicFolderBundle: it represents a Bundle object that ASP.NET creates from a folder that contains files of the same type.

Bundling and Minification It Reduces the request and size of the js and css resource file and thereby improving the responsiveness of our apps.

MVC have separate folders for Model, View and Controller. In the case of large projects, it becomes unmanageable with the default MVC structure. MVC 2 has introduced Area.
The area allows partitioning of large applications into smaller units, where each unit contains a separate folder structure, which is as the default MVC structure.
For  Example, Large applications may have different modules like admin, HR etc. So Area can contain separate MVC folder structure for each module.

Create MVC Area

To add MVC Area into your application, follow the below steps:

  1. Right-click to project solution explorer -> Add -> Area
  2. Enter the name of the area in the dialogue box and click Add button
  3. An area with a given name gets added with separate MVC folder structure.

When we want to use a code for pre-installed web API and MVC, we use scaffolding  .it is a quite quick process which interacts with the data model. The main use of adding scaffolding is to interact with code and data model fast. It reduces the amount of time to develop standard data operations in your project.

Scaffold templates are used to generate code for basic CRUD operations and writes a method specific to each DML operation against your database with the help Entity Framework. For this, they use Visual Studio T4 templating system to generate views.

Let's understand it with an example.

Let's create a simple class by the name of Employee.cs.

Add some properties to Employee class using the following code

using System;

namespace MVCScaffoldingDemo.Models {
  public class Employee{
     public int ID { get; set; }
     public string Name { get; set; }
     public DateTime JoiningDate { get; set; }
     public int Age { get; set; }
  }
}

We need to add another class, which will communicate with Entity Framework to retrieve and save the data.

using System;
using System.Data.Entity;

namespace MVCScaffoldingDemo.Models{
  public class Employee{
     public int ID { get; set; }
     public string Name { get; set; }
     public DateTime JoiningDate { get; set; }
     public int Age { get; set; }
  }

  public class EmpDBContext : DbContext{
     public DbSet<Employee> Employees { get; set; }
  }
}

As we know that EmpDBContext which is derived from the DB.Context class, In this class, we have one property with the name DbSet, which basically represents the entity which you want to query and save.

Validation Summary is used to visualise the error message in the unordered list which is in ModelStateDictionary object.we can display the validation error of each property which is defined under modal

ValidationSummary() Signature

MvcHtmlString ValidateMessage(bool excludePropertyErrors, string message, Object htmlAttributes)

If we want to show error message summary of the field which is defined under the modal then specify excludePropertyErrors = false.

To display field error in the validation summary

Syntax is @Html.ValidationSummary(false, "", new { @class = "text-danger" })

We can also display a custom error message using ValidationSummary. If Student name exists in the database then it will display the message.

To display a custom error message, first of all, you need to add custom errors into the ModelState in the appropriate action method.

Eg.

if (ModelState.IsValid)
{
bool nameAlreadyExists = * check database *
if(nameAlreadyExists)
{
ModelState.AddModelError(string.Empty,
"Student Name already exists.");
return View(std);
}
}

In this Validation Summary will automatically generate the error message into the modal state

we have to add the custom error messages using the ModelState.AddModelError method

The Different Validation overloading methods are :

1) ValidationSummary(HtmlHelper, Boolean, String, Object) :It Returns an unordered list of validation messages that are in the modelstatedictionary object and optionally displays only model-level errors.

2) ValidationSummary(HtmlHelper, Boolean, String, IDictionary<String,Object>) : it will            worked same as the ValidationSummary(HtmlHelper, Boolean, String, Object).

3) ValidationSummary(HtmlHelper, String, Object)

4) ValidationSummary(HtmlHelper, String, IDictionary<String,Object>)

5) ValidationSummary(HtmlHelper, Boolean, String)

6) ValidationSummary(HtmlHelper, String)

7) ValidationSummary(HtmlHelper, Boolean)

8) ValidationSummary(HtmlHelper)

Application life cycle is simply a series of steps or events used to handle some type of request or to change an application state.it uses the HTTP as a protocol to send the request on the browser, One thing that is true for all these platforms regardless of the technology is that understanding the processing pipeline can help you better leverage the features available and MVC is no different.

There are 2 different life cycle used in Asp.Net MVC:-

  1. Application Life Cycle
  2. Request Life Cycle

Application life cycle helps in getting to know that IIS will start working till its time will stop.

First, the request will find the routing method which is defined under the RouteConfig.cs, where there is a controller and its action method, is defined in the URL, after the controller has been created,actually begins running IIS until the time it stops,A component called the action invoker finds and selects an appropriate Action method to invoke the controller,MVC separates declaring the result from executing the result. If the result is a view type, the View Engine will be called and it's responsible for finding and rendering our view, If the result is not a view, the action result will execute on its own. It displays the actual HTTP result during the execution of the request

To make the development easy and simple as compared to asp.net web form application we use attribute routing, it is one of the different method which works differently routing

We used to define the routing in either Global.asax and RouteConfig.cs where this will decide which URL has to be chosen for the development

We need to put routes.MapMvcAttributeRoutes() in the routeconfig.cs which  enable attribute based routing on our MVC web application that can be done by only one line

Eg.

public static void RegisterRoutes(RouteCollection routes)

{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(  
name: "Default",  
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id =      UrlParameter.Optional }
);
}
In an action method, it is used like this
Eg.
[Route("products/{id?}")]
public ActionResult Details(string id)   
{
if (string.IsNullOrEmpty(id))
{
return View("List", GetProductList());
}
return View("Details", GetProductDetails());
}

Route Prefixes

We put the Route Prefix inside the controller which the request follow the route which is defined under the controller in the action method

Eg.

[RoutePrefix("products")]
public class ProductController : Controller
{
[Route]
public ActionResult List()
{
return View();
}
[Route("{id?}")]
public ActionResult Details(string id)
{
if (string.IsNullOrEmpty(id))  
{
return View("List");  
}
return View("Details");  
}
}

MVC routing uses the route table to look up and call the desired controller method, which renders the respected view. We can provide the routes in routeconfig file.

Sometimes it is required to have routes that are different from the ones configured in routeconfig and is specific to any controller or controller action method. In this attribute, routing comes into the picture.

To enable attribute based routing to add below line to routeconfig file under RegisterRoutes methods.

routes.MapMvcAttributeRoutes();

Samples of attribute routing:

  1. [Route(“products/{id?}”)]

    This route is to get a product with a given id. If id not provided then return all products

  1. [RoutePrefix(“products”)]

   This is places over the controller. All routes that start with products come to here

  1. [RouteArea(“business”)]

    RouteArea is a way to specify are in the route. It is just to let the route know that controller belongs to some area.

Description

Want to become an expert in cracking ASP.NET (Core) MVC interview questions? Start with practising the questions below. Crack your next MVC interview with the frequently asked questions.
Levels