From £99/Month
img
Last Updated: October 30, 2018

TOP 60 ASP.NET MVC Interview Questions With Answers

Asp-Net | Interview Questions

Asp.net MVC is one of the most popular frameworks with web developers and employers. With Full Microsoft backing and support for open source, this framework is becoming ever more popular. Here are some of the most important concept in the form of brief QA for a fantastic interview.

Table Of Contents


1. What is MVC (Model View Controller)
2. What is the difference between ASP.NET Core and ASP.NET MVC 5
3. In Which Assembly MVC Framework Is Defined?
4. What are the advantages of MVC
5. What are the new features added in version MVC5?
6. What are the different return types of a controller action method?
7. Page life cycle of MVC?
8. Can you explain the Razor View Engine?
9. What is meant by Separation of Concerns ?
10. What is a Controller?
11. What is a ViewModel?
12. Can you explain unrobustive Javascript
13. How do add JavaScript inside Razor View (inline)?
14. How to add Layout Section for the script
13. How do add JavaScript inside Razor View (inline)?
14. How To Handle 404 At Application Level In ASP.NET MVC?
15. What Is JSON Binding?
16. What Is Bundle.Config In ASP.NET 4.5?
17. How Is Routing Handled In Asp.Net MVC?
18. What Is ViewBag In Asp.Net MVC?
19. What Is ViewData In Asp.Net MVC?
20. What Is TempData In Asp.Net MVC?
21. What Is a Layout Page In Asp.Net MVC?
22. What common UI Can Be Added To A Layout Page?
23. What Is .Glimpse in MVC?
24. How Do We Link CSS Files In Razor Views?
25. What Are PartialViews In Asp.Net MVC?
26. What Route Constraints And They Implemented?
27. Explain Components Of A Route:
28. Are Views Shareable with Multiple Controllers?
29. What Is Scaffolding In Asp.Net MVC Application?
30. What Is RouteConfig.cs In Asp.Net MVC?
31. How Can I Use Javascript In Asp.Net MVC Views?
32. How Can I Add Css In Asp.Net MVC Views?
33. What Is HelperPage.IsAjax?
34. What Are Non Action methods in Asp.Net MVC And What Is The Use?
35. What Are Actionresult In Asp.Net MVC And What Are The Types?
36. Can We Change Action Name In Asp.Net MVC?
37. Explain ViewStart In Asp.Net MVC
38. What Is RenderBody In Asp.Net MVC?
39. What Is RenderPage In Asp.Net MVC?
40. How Can We Return JSON from action method In ASP.Net MVC?
41. What Is The Simplest Way To Return String From An Action In ASP.Net MVC?
42. What Is JQuery?
43. How To Include jQuery In ASP.Net MVC?
44. What Is jQuery Unobtrusive Validation In Asp.Net MVC?
45. How Can We Get All Selected checkboxes VALUES In jQuery?
46. Can We Run Different Versions Of jQuery On The Same Page?
47. How Can We Set Radio Button Selected Value Using Jquery In Asp.Net MVC?
48. How Can We RedirectToAction with parameter In ASP.NET MVC?
49. What Is REST (Representational State Transfer)?
50. What Is Test Driven Development (TDD)?
51. How Do We Carry Out Testing In Asp.Net MVC?
52. What Are Data Annotations In Asp.Net MVC?
53. How Can We Use Code Blocks In Views In Asp.Net MVC?
54. Describe The Folder Structure For Asp.Net MVC Application.
55. Explain HttpGet and HttpPost
56. What Is ORM(Object Relational Mapping) In Asp.NET?
57. How To Configure A Custom Error Page In asp.Net MVC?
58. What Is Validation Summary In Asp.Net MVC?
59. What Is Bundling In Asp.Net MVC?
60. What Is Minification In Asp.Net MVC?

1. What is MVC (Model View Controller)

MVC is a web application framework which employs a pattern for developing a web application. It divides an application into three separate components, Model-View-Controller.

The View is responsible for user interface Model represents the real world object/business entity and encapsulates properties and behaviour.

The Controller manages a user request and handles an appropriate model to be translated into an appropriate view.

Asp.net Model view controller quoracreative

2. What is the difference between ASP.NET Core and ASP.NET MVC 5

ASP.NET Core is a lean and composable framework for building web and cloud applications. ASP.NET Core is the fully open source.

Also, ASP.NET Core is cross-platform. We can develop ASP.NET Core web apps against the .NET core and run in either Windows or Linux or Mac.

Also, we can do develop in Windows OS, Linux, Mac using Visual Studio Code or any other code editors.

3. In Which Assembly MVC Framework Is Defined?

The MVC framework is defined in System.Web.Mvc.

4. What are the advantages of MVC

MVC provides separation of concern. It means we divide an application into Model, Control and View which helps to maintain our application. Each module is independent of each other which helps in reusability, maintenance and TTD (test-driven development).

5. What are the new features added in version MVC5?

OSX and Linux Support Cloud Optimization Unification of MVC and Web API Controllers Self Hosting Tag Helpers Dependency Injection Framework

6. What are the different return types of a controller action method?

ViewResult (View): It is the most common and used to return a webpage from an action method.

PartialviewResult (Partial view): This return type forms part of another view.

RedirectResult (Redirect): This return type is used to redirect to any other controller where the result could be processed further.

RedirectToRouteResult (RedirectToAction, RedirectToRoute): To redirect to any other action method.

ContentResult (Content): To only returns information such as content type as text/plain.

jsonResult (Json): This return type is used when we want to return a JSON (JavaScript Object Notation) message.

javascriptResult (javascript): This return type is used to return JavaScript code. the code then gets processed in the browser.

FileResult (File): This return type is used to send a file in binary format.

7. Page life cycle of MVC?

App initialization Routing Instantiate and execute controller Locate and invoke controller action Instantiate and render a view.

8. Can you explain the Razor View Engine?

Razor is a templating engine. It allows us to generate output like HTML. ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML. The idea behind Razor was to provide an optimized and minimal syntax for HTML generation using a code-focused templating approach.

@{ViewBag.Message = “Part1”;}
<div class=”heading”> <h3><em>@Model.ArticleTitle</em> </h3>    

9. What is meant by Separation of Concerns ?

It means separating a program into several modules to minimise overlapping of functionality and dependency. This greatly helps to facilitate maintenance and updates for the program.

10. What is a Controller?

A controller is a class. This class is the entry point for the request. A controller takes the request and connects the proper business logic and Model to prepare a response and returns it in the form of a View for User.

11. What is a ViewModel?

ViewModel is a class. It precisely binds to strongly typed View. When Validations are applied, It helps to reduce errors and perform better testing.

12. Can you explain unrobustive Javascript

Separation of HTML and JavaScript into separate files. Graceful degradation: If javascript is disabled or browser is not able to process javascript for any reason, important parts of the page still work. In simple terms, Onrobustive Javascript doesn't get in the way of other code in the program/webpage. It is more of JavaScript techniques and coding style.

13. How do add JavaScript inside Razor View (inline)?

To include a JavaScript function, it is as simple as including a "script" tag and defines the function inside the script block.

14. How to add Layout Section for the script

A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under the tag for scripts

<head>
 @RenderSection("scripts", required: false)
</head>

Now add a section name scripts using @section directive in the content view.

13. How do add JavaScript inside Razor View (inline)?

To include a JavaScript function, it is as simple as including a "script" tag and defines the function inside the script block.

14. How To Handle 404 At Application Level In ASP.NET MVC?

web.config

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404"  
  responseMode="ExecuteURL"path="/Error/PageNotFound" />
  </httpErrors>
</system.webServer>

ErrorController

{
  public ActionResult PageNotFound()
  {
    Response.StatusCode = 404;
    return View();
  }
}

15. What Is JSON Binding?

JavaScript Object Notation (JSON) binding provides support via JsonValueProviderFactory.

It enables action methods to send and receive JSON-formatted text.

It also enables action methods to model-bind the JSON text to parameters of action methods.

var person = getPerson();
var json = $.toJSON(person);

$.ajax({
    url: '/home/save',
    type: 'POST',
    dataType: 'json',
    data: json,
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        // get the result and do some magic with it
        var message = data.Message;
        $("#resultMessage").html(message);
    }
});

16. What Is Bundle.Config In ASP.NET 4.5?

As of Asp.Net MVC4, a standard ASP.NET MVC app has a file named BundleConfig.cs in the App_Start folder, by default.

It is a way to reduce the number of server requests that the browser needs to make to get all of these resource files.

Each time a browser has to load a resource, it has to make a separate HTTP(S) request to the server.

Server requests can greatly affect the page load speed which is negative for SEO and page rankings in search engines result in pages (SERPs).

BundleConfig is used to register the bundles by the bundling together and minification of common type of resources like script (.js) and style (css) files.

public class BundleConfig
{
  public static void RegisterBundles(BundleCollection bundles)
  {
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"));
  }
}

Embedded content: https://www.youtube.com/watch?v=gDMYzrC_zus

How To: Use and Add BundleConfig


Read More about: Bundling and Minification

17. How Is Routing Handled In Asp.Net MVC?

Routing in ASP.NET enables you to use URLs without mapping them to physical files in a Web application.

It has several advantages:

  • We can use URLs that are descriptive of the user's action.
  • As Urls are not linked to any physical file in an application, we have the freedom to return a response which serves the purpose and update when needs change.
  • We can use patterns to match requests, without including the names of those files in the URL

A routing table is enabled in your application's Web configuration file (Web.config file) by default.

public class MvcApplication : System.Web.HttpApplication
{
 public static void RegisterRoutes(RouteCollection routes)
 {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",          
        "{controller}/{action}/{id}",   
        new { controller = "Home", action = "Index", id = "" } 
    );
 }
 protected void Application_Start()
 {
    RegisterRoutes(RouteTable.Routes);
 }
}

Embedded content: https://www.youtube.com/watch?v=h_ARwj4_-fk

18. What Is ViewBag In Asp.Net MVC?

ViewBag property allows you to share values from a controller to the view.

ViewBag.Title = "Put your page title here";
ViewBag.Description = "Put your page description here";

ViewBag.UserNow = new User()
{
   Name = "Your Name",
   ID = 4,
};

To use these values in view, we need to use the same property names.

<h3>@ViewBag.Title</h3>

<p>@ViewBag.Description</p>
<p>Name: @iewBag.Name>
<p>ID:  @ViewBag.ID>

19. What Is ViewData In Asp.Net MVC?

ViewData is similar to ViewBag. It is a dictionary which can hold key-value pairs where each key must be a string.

ViewData only transfers data only one way, from the controller to view. It is valid only during the lifetime of a request.

In Controller

public ActionResult Index()  
{  
  ViewData["Company"] = "Quoracreative";    
  return View();  
}  

In View

<h2>Company Name: </h2> @ViewData["Company"]    

20. What Is TempData In Asp.Net MVC?

TempData can be used to store temporary data which can be used in the subsequent request only.

Use of TempData should be limited to non-sensitive data only.

It is a dictionary which can hold key-value pairs.

TempData can be used to transfer data from one action method to another action method.

public ActionResult Action1()
{
 TempData["CompanyName"] = "Quoracreative";
 return View();
}

public ActionResult Action2()
{
 if(TempData.ContainsKey("CompanyName"))
 string CompanyName = TempData["CompanyName"].ToString();    
}

21. What Is a Layout Page In Asp.Net MVC?

In an ASP.NET MVC application, a Layout is a view which contains common UI parts, so that we don't have to rewrite the same code over and over again in several pages.

22. What common UI Can Be Added To A Layout Page?

A Layout page can contain the common code necessary across multiple pages such as but not limited to:

  • Logo
  • Headers Section
  • Menus
  • Footer Sections
  • Resource links like Scripts and Style Sheets
  • Meta Tags

23. What Is .Glimpse in MVC?

Glimpse is a web debugging and diagnostics tool troubleshoot what's happening inside of your ASP.NET MVC 5.0 application routes.

Glimpse is an open source and is a client-side debugger.

Glimpse is a NuGet package. It provides detailed performance, is fast, super-light and provides a visual display for several performance matrices.

Get It here | Install-Package Glimpse.Mvc5 -Version 1.5.3

Read more:

Just as in any HTML page you can use the standard syntax:

<link rel=”StyleSheet” href=”/@Href(~Content/Site.css”)” type=”text/css”/>

25. What Are PartialViews In Asp.Net MVC?

Partialview help with re-usability.

Partial views can be used in a similar way like UserControls.

Partial views can be shared with multiple views.

Partial Views can be rendered in following to ways:

Html.Partial()
Html.RenderPartial()

26. What Route Constraints And They Implemented?

1. By using regular expressions:

Regular Expressions can be used to implement route constraints such as restricting the browser requests to match a particular route.

Say you only want to match URLs that contain an integer productId:

routes.MapRoute(
"Product",
"Product/{productId}",
 new {controller="Product", action="Details"},
 new {productId = @"\d+" }
 );

The regular expression \d+ matches one or more integers.

Following would match:

/Product/3
/Product/8999

2. By implementing the IRouteConstraint Interface:

You can implement a route constraint by implementing the IRouteConstraint interface like follows:

using System.Web;
using System.Web.Routing;
namespace MvcApplication1.Constraints
{
 public class LocalhostConstraint : IRouteConstraint
 {
  public bool Match
  (
  HttpContextBase httpContext, 
  Route route, 
  string parameterName, 
  RouteValueDictionary values, 
  RouteDirection routeDirection
  )
   {
    return httpContext.Request.IsLocal;
   }
  }
 }

27. Explain Components Of A Route:

Route Name: A name to distinguish route.

Pattern To Match: What to match.

Defaults: First Load, controller, action and any parameters

28. Are Views Shareable with Multiple Controllers?

You can directly return a different view in the same folder:

return View("NameOfView", Model);

Or you can make a partial view, put the view in the “Shared” folder and can return like:

return PartialView("PartialViewName", Model);

If the view is in different folder folder then, use absolute path:

return View("~/Views/FolderName/ViewName.aspx");

29. What Is Scaffolding In Asp.Net MVC Application?

ASP.NET Scaffolding is a framework for code generation for ASP.NET Web applications. You add scaffolding to your project to quickly add code standard code for a standard operation that interacts with data models.

Scaffolding can be used to generate the Controllers, Model and Views to create, read, update, and delete (CRUD) operations.

Following are the types of scaffoldings:

  • Empty
  • Create
  • Delete
  • Details
  • Edit
  • List

30. What Is RouteConfig.cs In Asp.Net MVC?

A Route defines the URL pattern and the information on how to handle it. Pre-configured routes are stored in RouteTable and are used the by Routing engine to determine appropriate handler class or file.

Routing can help define user-friendly URL(s) which are useful for Search Engine Optimization (SEO).

You provide routing information in RouteConfig.cs file:

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

     routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Funcionario", action = "AdicionarFuncionario", id = UrlParameter.Optional }
    );
   }
 }

31. How Can I Use Javascript In Asp.Net MVC Views?

Using Inlivne Javascript code:

<script type="text/javascript">
function AlertName(name)

 {
 alert('Javascript code called!");
 }
</script>

Using @RenderSection() directive:

JavaScript files can be bundled up in Bundle.config file and RenderSection can be added in the MVC Views to call add those script files:

Budle.config

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/jqueryval").Include(
                    "~/Scripts/somescript.js"));
      
    }
}

Call in Razor View:

<head>
   @RenderSection("scripts", required: false)
</head>

32. How Can I Add Css In Asp.Net MVC Views?

Using Inline code:

<head>
<link href="@Url.Content("~/Content/themes/base/Site.css")"
      rel="stylesheet" type="text/css" />
</head>

Using @RenderSection() directive:

CSS files can be bundled up in Bundle.config file and RenderSection can be added in the MVC Views to call add those files:

Budle.config

public class BundleConfig
{
 public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new       
        StyleBundle("~/Content").Include(
        "~/Content/themes/base/jquery.ui.core.css",
      
    }
}

Call in Razor View:

<head>
       @Scripts.Render("~/bundles/Content")
</head>

33. What Is HelperPage.IsAjax?

HelperPage.IsAjax Gets a value that indicates whether Ajax is being used during the request of the web page.

Namspace:

System.Web.WebPages  


public static bool IsAjax { get; }

It returns true if Ajax is used during the request and false if it isn't.

34. What Are Non Action methods in Asp.Net MVC And What Is The Use?

All public methods are by default treated as Actions in MVC Framework . If you do not want to use it as an action method, decorate it with “NonAction” attribute :

[NonAction]
public void TestMethod()
{
 // some logic
}

Uses:

There can be many scenarios:

  • If you implement some interface and do not want to call that public method.
  • Use [NonAction] attribute to restrict someones call to your action directly instead of having to go through the 'asd' function.
  • Make an action non-accessible from the navigation bar.
  • Avoid exposing an API endpoint during development

35. What Are Actionresult In Asp.Net MVC And What Are The Types?

ActionResults are a key component to ASP.NET MVC.

Every method in a controller class returns an ActionResult by default.

Action methods are used to return models to views, file streams, redirect to other controllers etc vis controller.

ASP.NET MVC ActionResults explained

Subtypes of ActionResult:

  • ViewResult
  • PartialViewResult
  • RedirectToRouteResult
  • RedirectResult
  • JavascriptResult
  • JSONResult
  • FileResult
  • HTTPStatusCodeResult

36. Can We Change Action Name In Asp.Net MVC?

There will be scenarios when you will need to change your action name. for example, Say you have an action method GetStudents() which returns a list of students enrolled in a program. You might not want to expose the actual action method to your clients.

You can use a different name in request URL which will map to GetStudents() method at runtime.

You can change the action name using the following syntax:

Public class StudentsController : Controller

[ActionName(“StudentsList”)]
{
 public ActionResult GetStudents()
 {
  return View();
 }
}

You can call GetStudent() action method using similar sytax:

http://{hostname}/Students/StudentsList

37. Explain ViewStart In Asp.Net MVC

The Asp.Net MVC Razor view engine will look for a file with the name ViewStart.cshtml and execute any code residing inside this file first, before executing the code inside an individual view file.

A common usage is to write code to point towards a Layout view which is used as a template across several views. Instead of adding code to declare the Layout page in every view, we can instead, use the _ViewStart page.

  @{ 
    Layout = "~/Views/Shared/__LayoutMain.cshtml";
  }

38. What Is RenderBody In Asp.Net MVC?

RenderBody is called to render the content of a child view.

The RenderBody method resides in the master / Layout page.

Only one RenderBody method can be used per Layout page.

RenderBody is like the ContentPlaceHolder.

 <html>
  <head> 
  </head>
  <body>
   <div id="main">
    @RenderBody()
   </div>   
  </body>
 </html>

39. What Is RenderPage In Asp.Net MVC?

RendersPage renders the specified view using a path and file name. In other words, It refers to a page on disk rather than an action method.

The RenderBody method also resides in the master / Layout page.

You can also supply a model you like which could be achieved using a parameter.

 <html>
  <head> 
  </head>
  <body>
   <div id="main">
   
    <h3>Breakfast:</h3>
     RenderPage("BreakfastMenue.cshtml")
    
    // using Model
    <h3>Lunch:</h3>
     RenderPage("TodaysLunchMenue.cshtml", LunchMenu)
     
   </div>   
  </body>
 </html>

40. How Can We Return JSON from action method In ASP.Net MVC?

public ActionResult GetProperties() {
 return JSON(new { prop1 = "Test1", prop2 = "Test2" });
}

Embedded content: https://www.youtube.com/watch?v=Oggn1mlQsOM

41. What Is The Simplest Way To Return String From An Action In ASP.Net MVC?

public ActionResult ReturnString() {
 return Content("Simple method returns string!!");
}

42. What Is JQuery?

JQuery is a JavaScript library. JQuery

  • has a cross-browser support
  • can be used to work on client-side.
  • is lightweight (write less, do more).
  • is fast
  • is small
  • is feature-rich
  • is Easy to learn
  • is Unobtrusive
  • has excellent API Documentation

You can use JQuery in your applications by downloading the latest version as a single .js file from the official web site.

Most companies like Google, Microsoft and IBM use jQuery.

JQueary makes it easy and simple to navigate to any element in HTML Document and manipulate it.

A quick look at what is available in jQuery:

  • Cross-browser support and detection.
  • AJAX functions
  • CSS functions
  • DOM Selection
  • DOM manipulation
  • DOM transversal
  • Special Effects
  • Attribute manipulation
  • Event detection and handling.
  • JavaScript animation
  • Utilities
  • Custom plugins

43. How To Include jQuery In ASP.Net MVC?

You can download and include the link to the script file directly in your page/master page using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Or, you can use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

Or, you can use NuGet Package Manager to install JQuery:

PM> Install-Package jQuery -Version 3.3.1

44. What Is jQuery Unobtrusive Validation In Asp.Net MVC?

It is Javascript validation that doesn't pollute your source code with its own validation code.

We don't need to call the validate() method as susual. Instead, we can specify requirements using data attributes in HTML.

<input type="text" name="email" data-val="true"> 

<div class="validation" data-valmsg-summary="true">
  <ul><li style="display:none"></li></ul>
</div>

45. How Can We Get All Selected checkboxes VALUES In jQuery?

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() { return this.value; }).get();

46. Can We Run Different Versions Of jQuery On The Same Page?

Sure, we can.

This is done by running different versions of jQuery in no-conflict mode.

<script src="jQuery1.3.js"></script>
<script>
jq13 = jQuery.noConflict(true);
  </script>

<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>

47. How Can We Set Radio Button Selected Value Using Jquery In Asp.Net MVC?

function RadionButtonSelectedValueSet(name, SelectdValue) {
$('input[name="' + name+ '"][value="' + SelectdValue +   '"]').prop('checked', true);
}

<script type="text/javascript">
jQuery(function(){
RadionButtonSelectedValueSet('RBLExperienceApplicable', '1');
})
</script>

48. How Can We RedirectToAction with parameter In ASP.NET MVC?

return RedirectToAction( "Main", new RouteValueDictionary( 
new { controller = controllerName, action = "Main", Id = Id } ) );

49. What Is REST (Representational State Transfer)?

REST is an architectural style or design pattern, for APIs, defined by Roy Fielding, a computer scientist. REST uses HTTP protocol methods like GET, POST, PUT, and DELETE to work with data.

ASP.Net MVC works in a similar style and provides full support for REST development.

50. What Is Test Driven Development (TDD)?

Test Driven Development is a development methodology in which we write tests first before we write the code.

Like any other development model, TDD, tests control your design and development cycles.

51. How Do We Carry Out Testing In Asp.Net MVC?

We can carry out unit testing using following frameworks for Asp.Net MVC applications:

  1. xUnit.NET
  2. NUnit
  3. MSTest
  4. MbUnit
  5. TestDriven.NET

52. What Are Data Annotations In Asp.Net MVC?

Validation is crucial for the smooth functioning of a web application.

It is not an easy task to implement.

Both Server side and client side techniques are used to make sure the data input correct.

Asp.Net MVC provides classes we can use to validate models using Data annotations attributes which are found in "System.ComponentModel.DataAnnotations" namespace.

These attributes provide server-side validation but client-side validation is also supported.

Here is an example for Data Annotation attributes:

  • Required: A Property is a required field
  • StringLength: Maximum length for a string field
  • Range: Maximum and minimum value for a numeric field
  • DisplayName: The text to display on form fields and validation messages
namespace School.Models
{
  public class Course
  {              
    [Required(ErrorMessage = "A Title is required")]
    [StringLength(160)]
    public string Title      { get; set; }

    [Range(1000, 2000,
    ErrorMessage = "Price must be between 1000 and 2000")]
    public int Price       { get; set; }
    [DisplayName("Course Name")]
    [StringLength(1024)]
    public string CourseName { get; set; }        
  }
}

53. How Can We Use Code Blocks In Views In Asp.Net MVC?

Using code blocks in Razor Views is simple. We need to encapsulate our code in in following @{ }

For single statement: @{ var message = "Your Message"; }

For multi statement:

@{
  var day = DateTime.Now.DayOfWeek;
  var message = "Hello, Happy " + day  + "!";
 }

54. Describe The Folder Structure For Asp.Net MVC Application.

  • App_Data: Can be used to store some application’s data files like .mdf database files and XML files etc
  • App_Start: Contains core configuration files / classes, applicable for entire application like RouteConfig, BundleConfig, etc.
  • Content: Contains static files, such as CSS files and images etc
  • Controllers: Contains application controllers.
  • Scripts: Contains JavaScript files.
  • Views: The folder contains a folder with a similar name for every controller and a shared folder for views used by more than one views/controllers.

55. Explain HttpGet and HttpPost

HttpGet and HttpPost are used to differentiate between betwwen request types for similar functionality.

Consider you want to implement Login functionality:

public ActionResult Login() {
return View();
}

public ActionResult Login(string userName, string password) {
return View();
}

How will you tell MVC to call appropriate method at each stage of the login process?

First, you can present a user with a login page with a GET request.

When user a enters the information you can use a POST request. This way, HttpGet and HttpPost restrict the action according to the type of request.

[HttpGet]
public ActionResult Login() {
}

[HttpPost]
public ActionResult Login(string userName, string password) {
return View();
}

56. What Is ORM(Object Relational Mapping) In Asp.NET?

An Object Relation Mapping(ORM) mechanism helps developers to address, access and manipulate data in applications by programming against a conceptual model instead of programming against a data source.

Benifits:

  • RDBMS independent data access layer
  • Rapid application development
  • Code reduction
  • Use of boilerplate methods for CRUD operations
  • Abstract access to data

Frameworks:

  • Microsoft Entity Framework
  • NHibernate
  • Microsoft LINQ to SQL
  • ORMapster

57. How To Configure A Custom Error Page In asp.Net MVC?

The HandleErrorAttribute allows you to use a custom page for the error.

Step 1. Update web.config file to allow your application to handle custom errors.

<system.web>  
  <customErrors mode="On">  
</system.web>  

Step 2. Mark your action method with the atttribute.

[HandleError]  
public class HomeController: Controller  
 {  
  [HandleError]  
  publicActionResultThrowException()  
  {  
   throw new ApplicationException();  
  }  
 } 

Step 3. Add HandleErrorAttribute on the action method.

[HandleError]  
public class HomeController: Controller   
{  
 [HandleError(View = "CustomErrorView")]  
 publicActionResultThrowException()   
 {  
   throw new ApplicationException();  
 }  
} 

58. What Is Validation Summary In Asp.Net MVC?

The ValidationSummary is a helper method that could be used to generate an unordered list of validation messages.

Validation messages are stored in the ModelStateDictionary object. You can add custom error methods as well:

if (ModelState.IsValid) {     
if(exists)
  {
    ModelState.AddModelError(string.Empty, "Name already exists.");
    return View(std);
  }
}

To display Errors in View:

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

59. What Is Bundling In Asp.Net MVC?

Bundling lets you combine more than one JavaScript (.js) files or more than one CSS (.css) files into one unit.

making it a single file reduces number of round requests to server, needed to download the resources, improving page load speed.

60. What Is Minification In Asp.Net MVC?

Minification squeezes out whitespace and performs compression to make the file small in size as much as possible without affecting

Disclaimer: “Whilst we have made every effort to ensure that the information we have provided is accurate, it is not and advice. We cannot accept any responsibility or liability for any errors or omissions. Visit third party sites at your own risk. This article does not constitute legal advice.

From £99/Month