What is the use of Keep and Peek in ASP.NET MVC TempData? | ASP.NET MVC Interview Question

IN ASP.NET MVC, Once TempData is read in the current request it will not be available in the subsequent requests. In order to make TempData in ASP.NET MVC to be read and also available in the subsequent request after reading, we need to call Keep method as shown in the code below.
@TempData[“MyData”];
TempData.Keep(“MyData”);

The same behavior can be achieved using Peek function in ASP.NET MVC. This function enables ASP.NET MVC to maintain TempData for the subsequent request.
string str = TempData.Peek("MyData").ToString();

Explain the Scope of TempData in ASP.NET MVC? | ASP.NET MVC Interview Question

TempData in ASP.NET MVC is available for the current request and in the subsequent request it’s available depending on whether TempData is read or not. So if ASP.NET MVC TempData is once read it will not be available in the subsequent request. In short, TempData in ASP.NET MVC is available till it is read.

What is the difference between HTML.TextBox vs HTML.TextBoxFor | ASP.NET MVC Interview Question

Both of them provide the same HTML output. However,  HTML.TextBoxFor is strongly typed while HTML.TextBox is not.

Below is a simple HTML code which just creates a simple textbox with 'CustomerName' as name.
Html.TextBox("CustomerName")

Below is Html.TextBoxFor code which creates HTML textbox using the property name ‘CustomerName' from object 'm'.
Html.TextBoxFor(m => m.CustomerName)

What are HTML helpers in ASP.NET MVC? | ASP.NET MVC Interview Question

HTML helpers help you to render HTML controls in the view. For instance if you want to display a
HTML textbox on the view, below is the HTML helper code.
<%= Html.TextBox("LastName") %>
For checkbox below is the HTML helper code. In this way we have HTML helper methods for every
HTML control that exists.
<%= Html.CheckBox("Married") %>

Explain ASP.NET MVC Application Life Cycle? | ASP.NET MVC Interview Question

Any web application has two main execution steps first understanding the request and depending on the type of the request sending out appropriate response. ASP.NET MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.



Creating the request object: - The request object creation has four major steps. Below is the detail
explanation of the same.

Step 1 Fill route: - ASP.NET MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route:- Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.

Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext”
object.

Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the
response as a result to the view.

Brief the Pros and Cons of ASP.NET MVC Razor View Engine? | ASP.NET MVC Interview Question

Pros:
  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC
Cons:
  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
Sample Razor Snippet:
@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}

Brief the Pros and Cons of ASP.NET MVC WebForm or ASPX View Engine? | ASP.NET MVC Interview Question

A view engine that is used to render a Web Forms page to the response.
Pros:
  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views
Cons:
  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates
Example:
<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
    <% foreach(var p in model){%>
    <li><%=p.Name%></li>
    <%}%>
</ul>
<%}else{%>
    <p>No products available</p>
<%}%>

What are Different Engines Avaible in ASP.NET MVC? | ASP.NET MVC Interview Question

View Engine is to provide an optimized syntax for HTML generation using a code-focused templating approach, Generally a view engine is parser for your code. There are two type of view engines available in ASP.NET MVC.

  • ASPX Engine or Webform Engine
  • Razor Engine

What are Bundling & Minification features in ASP.NET MVC 4? | ASP.NET MVC Interview Question

Bundling & Minification feature is introduced in MVC 4. Bundling & Minification reduces number of HTTP requests. Bundling & Minification combines individual files into single. Bundled file for CSS & scripts and then it reduce’s overall size by minifying the contents of the bundle.

What’s New in ASP.NET MVC 4 Mobile Template? | ASP.NET MVC Interview Question

Smart Phones & tablets touch got smart by using new jQuery.Mobile.MVC NuGet package.  The jQuery.Mobile.MVC NuGet Package for tablets and smart phones helps you to achieve the mobile project template touch optimized UI.

What is Routing in ASP.NET MVC? | ASP.NET MVC Interview Question | ASP.NET MVC Programmer Guide

, ,
In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but are not mapped to physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller.

Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller.

How to Specifying that a Parameter is Optional in MVC Attribute Routing? | ASP.Net MVC Interview Question

, ,
  • You can do it by Specifying that a parameter is Optional (via the '?' modifier).
  • This should be done after inline constraints.
  • Well,it's like this  [Route("Pet/{message:maxlength(4)?}")]
              
        PetController.cs

        // eg: /Pet/good
        [Route("Pet/{message:maxlength(4)?}")]
        public ActionResult PetMessage(string message)
        {
            return View();
        }

Key points of the above code
  • In the above example, /Pet/good and /Pet will Route to the PetMessage Action.
  • The route /Pet also works hence of the Optional modifier.
  • But /Pet/good-bye will not route above Action , because of the maxlength(4) constraint.

Above Routes on Browser are as below

parameter is Optional

How to Apply Multiple constraints to a Parameter in MVC Attribute Routing? | ASP.Net MVC Interview Question

, ,
  • You can apply multiple constraints to a parameter, separated by a colon.
  • Well,It's like this  [Route("Pet/{petId:int:min(1)}")]

 PetController.cs

     public class PetController : Controller
      {
        // eg: /Pet/8
        [Route("Pet/{petId:int:min(1)}")]
        public ActionResult GetSpecificPetById(int petId)
        {
            return View();
         }
     }

Key points of the above code
  • In the above example,You can't use  /Pet/10000000000 ,because it is larger than int.MaxValue
  • And also you can't use /Pet/0 ,because of the min(1) constraint.

How to set Route Constraints ? | ASP.Net MVC Interview Question

, ,
  • It allows you to restrict the parameters in the route template are matched
  • The syntax is {parameter:constraint}

     PetController.cs

     public class PetController : Controller
      {
        // eg: /Pet/8
        [Route("Pet/{petId:int}")]
        public ActionResult GetSpecificPetById(int petId)
        {
            return View();
         }
     }


Key points of the above code
  • In the above example, /Pet/8 will Route to the GetSpecificPetById Action.
  • Here the route will only be selected, if the "petId" portion of the URI is an integer.

Above Route on Browser is as below

Route Constraints





The following diagram shows the constraints that are supported

constraints list

Advantages of Attribute Routing Over the Convention-based Routing | ASP.NET MVC Interview Question

, ,
  • Attribute Routing gives you more control over the URIs in your web application
  • Easy to Troubleshoot issues
  • No fear of modifying anything will break another route down the line 

How to Assign Names to Routes? | ASP.Net MVC Interview Question

, ,
  • Specify a Name for a Route
  • By using that Name, you can easily allow URI generation for it
  • Well,It's like this : [Route("Booking", Name = "Payments")]

  BookingController.cs

 public class BookingController : Controller
    {
        // eg: /Booking
        [Route("Booking", Name = "Payments")]
        public ActionResult Payments() { return View(); }
    }

  • After that you can generate a Link is using Url.RouteUrl
  • It's like this : 
    <a href="@Url.RouteUrl("Payments")">Payments Screen</a>

Note : On the above code, "Payments" is a Route Name

How to override Default Route ? | ASP.Net MVC Interview Question

, ,
  • Use specific [Route] on a specific Action.
  • It'll override the default settings on the Controller.

       BookingController.cs

    [RoutePrefix("Booking")]
    [Route("{action=index}")]
    public class BookingController : Controller
    {
        // eg: /Booking
        public ActionResult Index() { return View(); }

        // eg: /Booking/Edit/3
        [Route("Edit/{bookId:int}")]
        public ActionResult Edit(int bookId) { return View(); }

    }

Above overridden Route on Browser is as below



How to use Default Route ? | ASP.Net MVC Interview Question

, ,


  • You can apply the [Route] attribute on the Controller level and put the Action as a parameter
  • That Route will then be applied on all Actions in the Controller
  • Well,It's like this : [Route("{action=index}")]
      
       BookingController.cs

    [RoutePrefix("Booking")]
    [Route("{action=index}")]
    public class BookingController : Controller
    {
        // eg: /Booking
        public ActionResult Index() { return View(); }

        // eg: /Booking/Show
        public ActionResult Show() { return View(); }

        // eg: /Booking/New
        public ActionResult New() { return View(); }

    }

Above Routes on Browser are as below

How to Override the Common Route Prefix? | ASP.Net MVC Interview Question

, ,
  • You can use a tilde (~) on the method attribute to override the route prefix
  • Well,It's like this : [Route("~/PetBooking")]
       
        BookingController.cs

    [RoutePrefix("Booking")]
    public class BookingController : Controller
    {
        // eg: /PetBooking
        [Route("~/PetBooking")]
        public ActionResult PetBooking() { return View(); }
    }

Above Route on Browser is as below

How to Set Common Route Prefix? | ASP.Net MVC Interview Question

, ,
  • If you want, you can specify a common prefix for an entire controller
  • To that you can use [RoutePrefix] attribute
  • It's like this : [RoutePrefix("Booking")]
    
       BookingController.cs

    [RoutePrefix("Booking")]
    public class BookingController : Controller
    {

        // eg: /Booking
        [Route]
        public ActionResult Index() { return View(); }

        // eg: /Booking/5
        [Route("{bookId}")]
        public ActionResult Show(int bookId) { return View(); }

        // eg: /Booking/5/Edit
        [Route("{bookId}/Edit")]
        public ActionResult Edit(int bookId) { return View(); }

    }

Above Routes on Browser are as below