Skip to main content

ASP.NET MVC Questions and Answers

Model View Controller (MVC)
· Model
· View
· Controller
Model(Business Layer): It is a business entity for representing the application data. 
Assembly used to define MVC framework

Advantages
· Provides a clean separation of UI, Model and Controller. Clear separation of application concerns (Presentation and Business Logic). It reduces complexity that makes it ideal for large scale applications where multiple teams are working.
· Easy to Unit test.
· Re-usability of Model and View. We can have multiple models can point to same view and vice versa.
· Improved code structure.
· Separation of Concerns (Process of breaking programs into various units)   
· Filters: The ASP.NET Web API uses most of built-in filters from MVC
· Model Binding & Validation: ASP.NET Web API uses same model binding functionality, but HTTP specific context related operations only.
· Routing changes: ASP.NET Web API uses same convention for config mapping that ASP.NET MVC provides.
· It’s an extensible as well as pluggable framework. We can plug components and further customize them easily.
· It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines).
· It supports for Test Driven Development (TDD) approach. In ASP.NET WebForms, testing support is dependent on Web Server but ASP.NET MVC makes it independent of Web Server, database or any other classes.
· Support for existing ASP.NET features like membership and roles, authentication and authorization, provider model and caching etc.

Exception handling in MVC
In the controller you can override the “OnException” event and set the “Result” to the view name.
public class HomeController : Controller
      var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");
      filterContext.Result = new ViewResult()
         }
For display the error in view
Web.Config file – ASP.Net routing has to be enabled
Global.asax file – Route table is created in the application Start event handler
· URL Pattern – Pass variables without using querystring by using placeholder.
· Handler - .aspx file or controller class
· Route Name – Optional
· Using Regular Expressions
· Using object which implements interface - IRouteConstraint.
· When a physical file is found that matches the URL pattern
· When routing is disabled for a URL pattern
Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.cs” and see the lengthy codes. For instance in the below code the developer can see right upfront that the “MyMethod” action can be invoked by four different URL structure. This is much user friendly as compared to scrolling through the “routeconfig.cs” file and going through the length line of code to figure out which URL structure is mapped to which action.
public class EmployeeController : Controller
· Temp data - Helps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.
· View data - Helps to maintain data when you move from controller to view.
· View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.
· Session variables - By using session variables we can maintain data from any entity to any entity.
· Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Differences
“TempData” maintains data for the complete request while “ViewData” maintains data only from Controller to the view.
Does “TempData” preserve data in the next request also?
“TempData” is available through out for the current request and in the subsequent request it’s available depending on whether “TempData” is read or not. So if “TempData” is once read it will not be available in the subsequent request.
What is the use of Keep and Peek in “TempData”?
TempData["Data];
The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek("Data").ToString();

View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.” There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.
· Web Form View Engine was with ASP.NET MVC since beginning.
· Razor View Engine was introduced later in MVC3.
· NHaml is an open source view engine since 2007.
· Spark is also an open source since 2008.
· .cshtml - for C# programming language
· .vbhtml - for VB programming language

A ViewModel basically acts as a single model object for multiple domain models, facilitating to have only one optimized object for View to render.  Multiple scenarios ViewModel becomes a choice like,
· Parent-Child View Scenario
· Reports where often aggregated data required
· Model object having lookup data
· Dashboards displaying data from multiple sources.

Partial view is a reusable view (like a user control) which can be embedded inside other view. 
For every page you would like to reuse, for example we can say header and footer controls.
So you can go and create partial views for header and footer. So we can create Partial view for these items and then you call that partial view in the main view.
Differences between Partial View and Display Template and Edit Templates
Display Templates : These are model centric. Meaning it depends on the properties of the view model used. It uses convention that will only display like divs or labels.
Edit Templates : These are also model centric but will have editable controls like Textboxes.
Partial View : These are view centric. These will differ from templates by the way they render the properties (Id's) 

Eg : CategoryViewModel has Product class property then it will be rendered as Model.Product.ProductName but in case of templates if we CategoryViewModel has List then @Html.DisplayFor(m => m.Products) works and it renders the template for each item of this list.

In ASP.Net MVC all public methods have been treated as Actions. So if you are creating a method and if you do not want to use it as an action method then the method has to be decorated with "NonAction" attribute

[NonAction]
"ActionName" attribute can be used for changing the action name.

[ActionName("ChangedAction")]
So in the above code "ChangeAction" is the original action name and in "ActionName" attribute name "ChangedAction" is given.
So the caller of this action method will use the name "ChangedAction" to call this action.
Multiple submit buttons in ASP.Net MVC
Below code gives you an idea about how we can do multiple submit buttons in same page,
// Save or Edit value will be sent to the Given method

Public ActionResult MyAction(string submit) {
}

CSRF attack and how can we prevent the same in MVC
CSRF stands for Cross site request forgery.
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.
All web application platforms are potentially vulnerable to CSRF (Cross-Site Request Forgery) attacks. The best way to prevent this attack in MVC application is to use Anti-Forgery token.

MVC Scaffolding
Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.
For this while creating MVC application we need to select one of the types of templates (leave the empty one).
eg: MVC 5 Controller with read/write actions
It creates controller code, view and also table structure.
Types of scaffoldings,
· Empty
· Create
· Delete
· Details
· Edit
· List

Display Mode in MVC

Display Mode displays views depending on the device and it handles different views for different devices.

For example below is a simple Employee Model object with “Name”, “Code” and "Experience" property.
EmployeeViewModel employeeVM= new EmployeeViewModel();

It has “Name”, “Code” and "Experience" plus “Experience Level” fields on the view / screen. 

“Experience Level”
If he is fresher up to 1 year experience then white color, 1 to 3 (juniour) year then green color, 3 to 6(mid) then blue color and above 6 is Seniour then red color. Means this is an extra property which is calculated on the basis of Experience.

So with the above fields we need to show “ExperienceLevelColor” which is depending on the “Experience“ value.

Here we can have multiple  logic's like Color transformation logic, Data format transformation logic etc.

We want to bind “Employee” and “Address” class to the view then we need to create a view model which aggregates both the classes and bind that view model with the view.

public class EmployeeAddressVM
In the view we can refer both the model using the view model as shown in the below code.

<%= model.employee.Name %>
<%= model.address.PostalCode %>

These techniques helps us to improve request load times of a page. This will result you good perfomance.

We may need to use multiple css and js files to your page.Bundling helps us combine multiple JavaScript and CSS files in to a single entity means it minimizing multiple requests in to a single request.

We implement this using BundleConfig.cs from the App_Start folder.

    public class BundleConfig
            // Javascript
            // Bundling/Minification has ordering built in internally. To override this and force an order of files manually, call the Clear().

If you are in a debug mode, you need to set EnableOptimizations to true in the bundleconfig.cs file or else you will not see the bundling effect in the page requests.
BundleTable.EnableOptimizations = true;

Minification reduces the size of script and CSS files by removing blank spaces , comments etc.
For example below is a simple JavaScript code with comments.

function Example() {
After implementing minification the JavaScript code looks like below. You can see how whitespaces and comments are removed to minimize file size, thus increasing performance.

function Example(){$(".loadingSmall").remove();var Name=$("#Name").val();
var trimName=$.trim(Name);
if(!isValidName(trimName))$("#mainFields").hide();
else
{$("#Button").after("<span class='loadingSmall help-inline'></span>");
getFunction();
$("#mainFields").show()}}

· Implement post-processing logic before the action happens.
· Cancel a current execution.
· Inspect the returned value.
· Provide extra data to the action.
· Inline action filter.
· Creating an ActionFilter attribute.
· Authorization filters
· Action filters
· Response filters
· Exception filters

1) ViewResult - Renders a specified view to the response stream
2) PartialViewResult - Renders a specified partial view to the response stream
3) EmptyResult - An empty response is returned
4) RedirectResult - Performs an HTTP redirection to a specified URL
5) RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
6) JsonResult - Serializes a given ViewData object to JSON format
7) JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8) ContentResult - Writes content to the response stream without requiring a view
9) FileContentResult - Returns a file to the client
10) FileStreamResult - Returns a file to the client, which is provided by a Stream
11) FilePathResult - Returns a file to the client

Create a class which implements the IView interface. In this class we should write the logic of how the view will be rendered in the render function.
Create a class which inherits from VirtualPathProviderViewEngine and in this class we need to provide the folder path and the extension of the view name. For instance, for Razor the extension is “cshtml”; for aspx, the view extension is “.aspx”, so in the same way for our custom view, we need to provide an extension. 
Register the view in the custom view collection. The best place to register the custom view engine in the ViewEngines collection is the global.asax file. 
· Presentation: It is the visual representation of a specific abstraction within the application.
· Abstraction: It is the business domain functionality within the application.
· Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system
ASP.NET Web API is included in ASP.NET MVC which obviously increases TDD (Test Data Driven) approach in the development of RESTful services.
For developing RESTful services in WCF you still needs lot of config settings, URI templates, contract’s & endpoints which developing RESTful services using web API is simple.
· The model pattern is little complex
· Inefficiency of data access in view
· With modern user interface, it is difficult to use MVC
· You need multiple programmers for parallel development
· Multiple technologies knowledge is required


ASP.NET MVC is a web application framework developed by Microsoft. It is a pattern which is used to split the application implementation logic into three components.



View(Presentation Layer): It is a presentation layer for ASP.NET MVC
Controller(Input Control): It is a separate view component to generate HTML page for the request.             ControllerBase class is the base class for all Controllers. The request which is sent by the user is always scatters through controller and its responsibility is to redirect to the specific View.

System.Web.Mvc – Contains all the classes and interface that support MVC

Namespaces using for adding MVC to an old ASP.Net Application

System.Web.Routing
System.Web.Abstraction
System.Web.Mvc

DataAnnotations

One of the easiest way to doing validation in MVC is DataAnnotations. These are the attributes can applied on Model properties directly. There are multiple type of validations are available.

1. Required data annotation attribute
   If the model is not provided data then it will not accept.
   eg: Class Employee having Employee name is a required field.
       
         Public Class Employee
         {
               [Required(ErrorMessage="Employee Name is required")]
               public string employeeName {set; get;} 
         }  

        For displaying validation error message we have to use the ValidateMessageFor method which belongs to the Html helper class.

       <% using (Html.BeginForm("postEmployee", "Home", FormMethod.Post))
       { %>
              <%=Html.TextBoxFor(m => m.employeeName)%>
              <%=Html.ValidationMessageFor(m => m.employeeName)%>
       <%}%> 
        
       Here the Employee Name tagged with the required data annotation attribute. If Employee model is not provide Employee Name then it won't allow you to submit.

How we can check the model is properly validated?

Using ModelState.IsValid property.


public ActionResult postEmployee(Employee employee)
{
     if (ModelState.IsValid)
     {
         employee.Save();
         return View("EmployeeList");
     }
     else
     {
         return View("Employee");
     }
}

Validation Summary

ValidationSummary from html helper class. 

       <%= Html.ValidationSummary() %> 

Here we can display all errors in one place.

2. String Length Attribute

Using the below code you can check string length, and it wont accept the string having more than 100 letters.


[StringLength(100)]
public string employeeName{ get; set; }

3. Range Attribute

We can use range for validating the data in between two numbers.

[Range(10000,80000)]
public int Salary{ get; set; }

4. Compare Attribute

We can compare one field value with other fields value then we can use this. Please see the below code,

public string password { get; set; }

[Compare("password")]
public string confirmPassword { get; set; }

5. Regular Expression Attribute

We can validate like email, mobile number etc.

[RegularExpression(@"^9\d{9}$")]
public string mobileNumber{ get; set; }

 6. For getting a particular error message, we can use the Errors Collection.

     var error =  ModelState["Name"].Error[0].ErrorMessage

How we can explicitly check the object is valid or not

Using TryUpdateModel. 

TryUpdateModel(Employee);

How we can add error from Controller

Using AddModelError function.

      ModelState.AddModelError("Name","Error Message");

There are two process to enable data annotation validation on client side.

1. Reference the JQuery file
2. Call EnableClientValidation Method.

       <% Html.EnableClientValidation(); %> 

How to use Jquery Plugins in ASP.Net MVC validation?


If we want to use validation during runtime using Jquery then we can use Jquery plugins for validation. 

Eg: Validation for Employee name textbox 

$('#employeeName').rules("add", {
required: true,
minlength: 4,
messages: {
required: "Please enter Employee Name",
minlength: "Minimum length is 4"
}
});



  {
         protected override void OnException(ExceptionContext filterContext)
         {
             Exception ex = filterContext.Exception;
             filterContext.ExceptionHandled = true;


{
                 ViewName = "Error",
                 ViewData = new ViewDataDictionary(model)
      };

}

@Model.Exception;

Namespace for DataAnnotation in MVC

System.ComponentModel namespace is used to display DataAnnotation in MVC
System.ComponentModel.DataAnnotations namespace is required to DataAnnotation using MVC. System.Web.Helpers is using for check valid model state for data annotations.

Routing

Its a stand alone component - Match requests to IHttpHandlers by URL pattern
MVCHandlers itself an IHttpHandlers - act as kind of proxy to other IHttpHandlers configured
in Routing table.

We have to do settings in 2 place for Routing works in MVC Applications

Advantages of using Routing

If we are not using Routing, then the browser request should be mapped to a physical file. There 
Is a chance to get an error if the file is not available. If we use Routing, then there is no need of 
Mapping to specific files in a website. Routing will take care of URLS and there is no need to map a file. 
URLs describe user action and there for users can easily understand.

Required to Specify a Route

Significance of ASP.NET routing

Default Route Name:
"{controller}/{action}/{id}", // URL with parameters
By default routing is defined under Global.asax file. MVC ASP.Net uses routing to map between incoming browser request to controller action methods.

Use of "{resource}.axd/{*pathInfo}" in routing

Using this default route - {resource}.axd/{*pathInfo}, we can prevent the requests for the web resources files like - WebResource.axd or ScriptResource.axd from passing to a controller.

Add constraints to the route

we can add constraints to route in following ways,
Where routing is not implemented or required

Attribute Routing

ASP.NET Web API supports this attribute routing. This is introduced in ASP.Net MVC5.
Here attributes are being used to define the routes.It will give more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level,

    Controller Level: [Route("{action = employeeList}")] 

    Action Level: [Route("Employee/{EmployeeID:int:min(10)}")] 

To enable attribute routing as shown below:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //enabling attribute routing
        routes.MapASP.Net MVCAttributeRoutes();
        //convention-based routing
        routes.MapRoute
        (
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Employee", action = "GetEmployeeList", id = UrlParameter.Optional }
        );
    }

Difference between adding routes, to a webform application and an MVC application?

To add routes to a webform application, we can use MapPageRoute() method of the RouteCollection class, where adding routes to an MVC application, you can use MapRoute() method.

What is the advantage of defining route structures in the code?


{
       [Route("Employee/EmployeeDetails")]
       [Route("Employee/MyProjects")]
       [Route("Employee/MyTeam")]
       [Route("Employee/MyManagers")]
       public ActionResult MyMethod()
       {
           return View();
       }

}

Page Life cycle

1. App Initialization

Global.asax --> Application_Start()--> Add Rout Object to RouteTable.Routes--> Implement a Custome IControllerFactory --> Active Controller Factory by assiging it to System.Web.Mvc.ControllerFactory.Instance Property

2. Routing

Its a stand alone component - Matchs requests to IHttpHandlers by URL pattern MVCHandlers itself an IHttpHandlers - act as kind of proxy to other IHttpHandlers configured in Routing table.

3. Instantiate and Execute Controller

the Active IControllerFactory supplies an IController Instance

4. Locate and invoke controller action

the controller invokes its relevant action methods after RenderView()

5. Instantiate and render view

the IViewFactory supplies an Iview, which pushes response data to the IHttpResponse object.


ViewData, ViewBag and TempData

Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

In order to pass data from controller to view, Controller to Controller (One Entity to another Entity) and in next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag and TempData. Both ViewBag and ViewData are used to to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism to maintain state between controller and corresponding view. ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn’t have typecasting and null checks. TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects i.e from one controller to the other controller. 




What is difference between TempData and ViewData ?

Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.

TempData.Keep(Data);

RenderBody and RenderPage in ASP.Net MVC

RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will render the child pages/views. Layout page will have only one RenderBody() method. RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout page.

ViewStart Page in ASP.Net MVC

This page is used to make sure common layout page will be used for multiple views. Code written in this file will be executed first when application is being loaded.

Methods used to render the views in ASP.Net MVC

Below are the methods used to render the views from action -
• View() : To return the view from action.
• PartialView() : To return the partial view from action.
• RedirectToAction() : To Redirect to different action which can be in same controller or in different controller.
• Redirect() : Similar to "Response.Redirect()" in webforms, used to redirect to specified URL.
• RedirectToRoute() : Redirect to action from the specified URL but URL in the route table has been matched.

partial views in MVC


For creating a partial view then while adding a view to your project you need to check the “Create partial view” check box. Then you can call the partial view in the main view using the Html.RenderPartial("PartialViewName").

Non Action methods in ASP.Net MVC


public void NonActionMethod()
{
// logic
}


How to change the action name in ASP.Net MVC?


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

@using (Html.BeginForm("MyAction","MyController")
{
    <input type="submit" value="Save" />
    <input type="submit" value="Edit" />
}

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model. Many times HTML UI names are different than the model property names. So in the binder we can write the mapping logic between the UI and the model.

Scaffolding use Entity framework to internally connect to the database.

For example Employee.aspx render for desktop and Employee.Mobile.aspx for mobiles. Now depend on the request display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

View Model in ASP.Net MVC

View model is a plain class with properties. View model is used to bind strongly typed View. Here we can do validation using DataAnnotation.


employeeVM.Employee.Name = "Jom";
employeeVM.Employee.Code = 0303;
employeeVM.Employee.Experience = 6;

is a color indication which indicates how seniour he is depends on the value of the “Experience" property.


Multiple models with a single view


{
public Employee employee = new Employee();
public Address address = new Address();
}

Bundling and Minification in MVC


    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            // CSS
            bundles.Add(new StyleBundle("~/bundles/css/Employee").Include(
                "~/Content/PageSpecific/Employee.css"));

            bundles.Add(new ScriptBundle("~/bundles/js/Site").Include(
                "~/Scripts/jQuery/jquery-1.8.1.js",
                "~/Scripts/main-site.chirp.js"
            ));
            bundles.Add(new ScriptBundle("~/bundles/js/Site1").Include(
                "~/Scripts/jQuery/Bootstrap/bootstrap-dropdown.chirp.js",
                "~/Scripts/jQuery/Bootstrap/bootstrap-alert.chirp.js",
                "~/Scripts/jQuery/Bootstrap/bootstrap-tooltip.chirp.js",
                "~/Scripts/main-site.chirp.js",
                "~/Scripts/Employee.js"
            ));

            bundles.FileSetOrderList.Clear();
        }
    }


$(".loadingSmall").remove();
var Value = $("#Name").val();
var trimName = $.trim(Name); //trim using jquery trim
if (!isValidName(trimName)) {
$("#mainFields").hide();
}
else {
        $("#SaveButton").after("<span class='loadingSmall help-inline'></span>");
        getFunction();   
   $("#mainFields").show();
}
}

Detecting an MVC controller is called by POST or GET

we can use the Request.HttpMethodproperty

public ActionResult SomeAction()
{
     if (Request.HttpMethod == "POST")
     {
         // Code
     }
     else
     {
         // Code
     }
}

JSON Binding

JavaScript Object Notation (JSON) binding support via the new JsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.

Dependency Resolution

Dependency Resolver is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.

Important namespaces used in ASP.Net MVC 

System.Web.ASP.Net MVC
System.Web.ASP.Net MVC.Ajax
System.Web.ASP.Net MVC.Html
System.Web.ASP.Net MVC.Async

AJAX Helpers in ASP.Net MVC

AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs the request asynchronously.

Below are the options in AJAX helpers :

Url : This is the request URL.
Confirm : This is used to specify the message which is to be displayed in confirm box.
OnBegin : Javascript method name to be given here and this will be called before the AJAX request.
OnComplete : Javascript method name to be given here and this will be called at the end of AJAX request.
OnSuccess - Javascript method name to be given here and this will be called when AJAX request is successful.
OnFailure - Javascript method name to be given here and this will be called when AJAX request is failed.
UpdateTargetId : Target element which is populated from the action returning HTML

The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request of the Web page.

Layout in ASP.Net MVC

Layout pages are similar to master pages in traditional web forms. This is used to set the common look across multiple pages. 

In Child pages,

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

Sections is ASP.Net MVC

Section are the part of HTML which is to be rendered in layout page. 

@RenderSection("Section")

in the child page,

@section Section{
<h1>Title<h1>
}

If any child page does not have this section defined then error will be thrown so to avoid that,

@RenderSection("TestSection", required: false)

Code Blocks in Views

Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that are executed. This is useful for declaring variables which we may be required to be used later.

@{
var i =0;
int j =1;
string Name=Jom;
 }


What symbol would you use to denote, the start of a code block in razor views?

@

What symbol would you use to denote, the start of a code block in aspx views?

<%= %>

Calling a JavaScript function on the change of a Dropdown List in ASP.Net MVC

Create a JavaScript method

function FillEmployee() { }

Invoke the method using below code

< %:Html.DropDownListFor(x => x.SelectedEmployee, new SelectList(Model.Name, "Value", "Text"), "Please Select an Employee", new { id = "ddlEmployee", onchange=" FillEmployee()" })%>

Html.Partial in ASP.Net MVC

Used for render the specified partial view as an HTML string and does not depend on any action methods. 

@Html.Partial("PartialViewName")

Html.RenderPartial

"RenderPartial" is directly written to the HTML response and returns void (Nothing).

This method also does not depend on action methods. 

RenderPartial() method calls "Write()" internally and we have to make sure that "RenderPartial" method is enclosed in the bracket. 

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

Adding the CSS in ASP.Net MVC

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

Glimpse in ASP.Net MVC

Glimpse is an open source tool for debugging the routes in ASP.Net MVC. It is the client side debugger, Which tracks the speed details, url details etc.

Action Filters in ASP.Net MVC

Action Filters allow us to execute the code before or after action has been executed. This can be done by decorating the action methods of controls with ASP.Net MVC attributes.

Action filters are useful in the following scenarios:

You can create action filters by two ways:
To create an inline action attribute we need to implement the IActionFilter interface. The IActionFilterinterface has two methods: OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods. The problem with the inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from ActionFilterAttribute and implement the IActionFilter interface.Later we can decorate the controllers on which we want the action attribute to execute.

Different types of action filters with the sequence for execution,
Example for Authorization filters in an asp.net mvc application

1. RequireHttpsAttribute
2. AuthorizeAttribute

OutputCacheAttribute class represents Result Filter

AuthConfig.cs in ASP.Net MVC 

AuthConfig.cs is used to configure security settings including sites oAuth Login. This file is under App_Start.

Determine action invoked from HTTP GET or HTTP POST

Use class : "HttpRequestBase" and use the method : "HttpMethod" to determine the action request type.


In Server how to check whether model has error or not in ASP.Net MVC?

Whenever validation fails it will be tracked in ModelState. 

By using property "IsValid" we can determine. 

if(ModelState.IsValid){
      // No Validation Errors
}


How to make sure Client Validation is enabled in ASP.Net MVC?

In Web.Config there are tags called : "ClientValidationEnabled" and "UnobtrusiveJavaScriptEnabled". 

We can set like,

< add key="ClientValidationEnabled" value="true" />
< add key="UnobtrusiveJavaScriptEnabled" value="true" />

This setting will be applied at the application level.

Unobtrusive JavaScript

This is a general term that conveys a general philosophy, similar to the term REST. Unobtrusive JavaScript doesn't intermix JavaScript code in your page markup. 

Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes

ActionLink

using this hyperlink option we can navigate from one view to other view.

The below code will make a simple URL which help to navigate to the “Employee” controller and invoke the “EmpDetails” action.

<%= Html.ActionLink(“Employee”, “EmpDetails”) %>

How to get a value of an element by name instead of ID

$('#id').val();
$("input[name=nameGoesHere").val();
$('name=nameGoeshere]').val();
$(".yourclass").val();

Use of hidden field

<input type="hidden" id="idname" name="Name" value="Company" />

alert($('input# idname ').val());
alert($('input[name= Name]').val());
alert($('input[type=hidden]').val());
alert($(':hidden# idname ').val());
alert($('input:hidden[name= Name]').val());

Pass a datetime with format from javascript to Controller

Get method:

$.get('/example/doGet?date='+ new Date().toISOString(), function (result
{console.log(result);
});
[HttpGet]
public JsonResult DoGet(DateTime date)
{
Return Json(date.ToString(), JsonRequestBehavior.AllowGet);

Post method: 

$.post('example/do', {date: date.toISOString() }. function (result)
{
console.log(result);
});

[HttpPost]
public JsonResult Do(DateTime date)
return Json(date.ToString());
}

Example for an Ajax call

function getDetails(){
$.ajax({
type: "POST",
async: true,
cache: false,
datatype: "json",
url="/JG/Employee/GetDetails",
data: {"FirstName":$("#txtFirstName").val(), "LastName" : $("#txtLastName").val():,
beforeSend: function()
{
$("#divname").addClass("loadingSmall");
}
, error: function (jsonDara, textStatus, errorThrown){
alert("there an error "+errorThrown);
//do code.......
}
, complete: function(jsonData, textStatus) {
$("#divname").removeClass("loadingSmall");
}
, success: function(data, textStatus) {
//Code here
}
}); 
}
}

Razor View Engine
It’s a rendering framework in ASP.Net webpages. We can reduce the code using syntax change. Given below example give an idea,

Eg: Rendering in ASP.Net
<ul>
<% foreach (var userTicket in Model)
{ %>
<li> <%: userTicket.value %> </li>
<% } %>
</ul>

By Using Razor
<ul>
@foreach (var userTicket in Model)
<li> @userTicket.value </li>
</ul>


NonActionAttribute – changing the default behavior by using Action Methods.

Router Table formation

Beginning stage --> Application_Starts() method called
--> In Application_Start() method calls RegisterRoutes() method
--> The Register_Routes method will create the Router table.

Segments of Default Route
3 Segments
1. Controller Name (Search)
2. Action Method Name (label)
3. Parameter passed to Action Method Name (Parameter Id – MVC)

 How to avoid XSS Vulnerabilities in ASP.Net MVC?

We have to use syntax as ‘<%: %>’ instead of ‘<%= %>

This because it does the HTML encoding
Eg: <input type=”text” value=”<%: value%>” />

Area in ASP.Net MVC

Area is used to store the details of the modules of our project. This is really helpful for big applications, where controllers, views and models are all in main controller, view and model folders and it is very difficult to manage.

for registration,

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}

Difference between “HTML.TextBox” vs “HTML.TextBoxFor”

Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. 

Textbox with “EmployeeName” as name.

Html.TextBox("EmployeeName")

Textbox using the property name ‘EmployeeName” from object “m”.

Html.TextBoxFor(m => m.EmployeeName)


Different types of results in MVC

There 12 kinds of results in MVC, at the top is the ActionResult class is an abstract class. which is a base class that can have 11 sub types are listed below,
Difference between ActionResult and ViewResult

ActionResult is an abstract class while ViewResult derives from the ActionResult class.
ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of views dynamically, ActionResult is the best thing. 

Authentication and Authorization in MVC

For Windows authentication you need to modify the web.config file,

<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization> 

Then in the controller or on the action, you can use the Authorize attribute which specifies which users have access to these controllers and actions.

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class EmployeeController : Controller
{
     [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
     public ActionResult Index()
     {
         // Code
     }

For Form Authentication we have to set the authentication mode equal to Forms. 

<authentication mode="Forms">
<forms SignInUrl="~/Home/SignIn"  timeout="3000"/>
</authentication> 

Here we will do the validation and if its success then we will set the cookie value.

 System.Web.Security.FormsAuthentication.SetAuthCookie(UserName, RememberMe); 
//RememberMe is a Boolean value 

Here all actions need to be attributed with the [Authorize] attribute.

[Authorize]
Public ActionResult SignIn()
{
  // Code
}

Here not allow to make a call to these controllers from an unauthorized user.

Creating our custom view engine using MVC

How we can use Razor code in Javascript in ASP.Net MVC?

We can use the razor code in javascript in cshtml by using <text> element.


Role of components Presentation, Abstraction and Control in MVC
Child actions in ASP.Net MVC

To create reusable widgets child actions are used and this will be embedded into the parent views. In ASP.Net MVC Partial views are used to have reusability in the application. Child action mainly returns the partial views.

"ChildActionOnly" attribute is decorated over action methods to indicate that action method is a child action.

[ChildActionOnly]
public ActionResult MyMethod()
{
//Logic here
return PartialView();
}

ASP.NET MVC HtmlHelpers

HtmlHelper basically is a method that returns a string.So, in ASP.NET MVC we have HtmlHelpers for links, Images and for Html form elements etc. 

1. @Html.ActionLink(“Company Profile”, “CompanyInfo”)

         will render
         <a href=”/Company/CompanyInfo”>Company Profile</a>


2. @Html.TextBox(“txtEmployeeName”) 

         will renders
        <input id=”txtEmployeeName” name=”txtEmployeeName” type=”text” value=”” />

Restrict MVC actions to be invoked only by GET or POST

We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. 


[HttpGet]
public ViewResult getEmployee(int id)
{
    Employee employee = Employee[id];
    return View("EmployeeDetails",employee);


If we try to make HTTP POST on getEmployee then it will throw an error.


Test Driven Development (TDD) 

TDD is a methodology which says, write your tests first before you write your code. In TDD, tests drive your application design and development cycles. You do not do the check-in of your code into source control until all of your unit tests pass.

 Representational State Transfer (REST) 

REST is an architectural style which uses HTTP protocol methods like GET, POST, PUT, and DELETE to access the data. ASP.Net MVC works in this style. In ASP.Net MVC 4 there is a support for Web API which uses to build the service using HTTP verbs.

WebAPI

WebAPI is the technology by which you can expose data over HTTP following REST principles. HTTP is the most used protocol. For the past many years, browser was the most preferred client by which we consumed data exposed over HTTP. But as years passed by, client variety started spreading out. We had demand to consume data on HTTP from clients like mobile, JavaScript, Windows applications, etc. For satisfying the broad range of clients REST was the proposed approach. 

we can also develop the RESTful services with WCF, but there are two main reasons that prompt users to use Web API instead of RESTful services.

Bootstrap in MVC5

Bootstrap (a front-end framework) is an open source collection of tools that contains HTML and CSS-based design templates along with Javascript to create a responsive design for web applications. Bootstrap provides a base collection including layouts, base CSS, JavaScript widgets, customizable components and plugins. Project Template in ASP.NET MVC5 is now using bootstrap that enhances look and feel with easy customization. 

Third party View Engine using ASP.Net MVC Engine 

Spark (Castle MonoRail framework projects), Open Sourced, it is popular as MVCContrib library.
NHaml works like inline page templating.
NDjango uses F# Language.
Hasic uses VB.Net, XML.
Bellevue for ASP.NEt view, It respects HTML class first.

Some common Objective questions

1. In which format data can be return from XML into table ?

     DataSet

2. Can we use view state in MVC ?

     No

3. What Request Processing technique follows ASP.Net ?

     Pipeline

4. What is DRY principle in ASP.Net ?

     Don't repeat yourself.

5. What is default authentication in Internet Information Services (IIS)?

    Anonymous

6. How can you comment using Razor Syntax?

    @* Comment me *@

7. Which Namespace is used for Razor View Engine ?

    System.Web.Razor

8. Which Namespace is used for ASPX View Engine ?

    System.Web.Mvc.WebFormViewEngine

9. Which is more faster between ASPX View Engine and Razor View Engine.

    ASPX View Engine

10. Does Razor Engine supports for TDD ?

    Yes

11. Does ASPX View Engine supports for TDD ?

     No

12. What is the difference between MVC (Model View Controller) and MVP (Model View Presenter)?

      MVC controller handles all the requests, MVP handles as the handler and also handles the all             requests as well.

13. Does Viewstart override all Views layout/template under "Views" folder in MVC ?

      Yes 

14. What is the name of default Viewstart Page in ASP.Net MVC ?

     _ViewStart.cshtml 


BundleConfig.cs in ASP.Net MVC 

BBundleConfig.cs in MVC is used to register bundles used by the bundling and minification, serveral bundles are added by default like jQuery, jQueryUI, jQuery  validation, Modernizr, default CSS references. 

FilterConfig.cs in ASP.Net MVC 

FilterConfig.cs is used to register global MVC filters, HandleErrorAttribute is registered by default filter. We can also register other filters.

15. How to check Request coming from which controller using MVC ASP.Net?

      var _controller =             HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();

16. How can we provide Height and Width to MVC Charts ?

      new Chart(width: 600, height: 400)

17. How can we set theme to MVC Charts?

      new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D) 

18. How can we give Title to MVC Charts?

     .AddTitle("My First Chart") 

19. How can we add Series to MVC Charts?

      AddSeries(chartType: "Bar", xValue: xValue, yValues: yValue) 

20. How can we add Chart Type to MVC Charts?

     AddSeries(chartType: "Bar") 

21. How can we write Chart output to MVC View? 

     Write("bmp"); 

22. Which name space using can send email in ASP.Net MVC?

       using System.Net.Mail; 
       MailMessage mail = new MailMessage();

23. If Razor View Engine need to add JQuery function and contain @ special character then how we can write it in Razor View? 
       Replace @ to @@ (double)  

24. How to set Default Value to Hidden Input Box using ASP.Net MVC? 

       @Html.HiddenFor(m => m.Name, new { Value = "Jack"})  

25. How to check all errors of Model using ASP.Net MVC? 

      var errors = ModelState.Values.SelectMany(v => v.Errors); 

26. BundleConfig.cs file is under in which App folder ? 

      App_Start 

27. FilterConfig.cs file is under in which App folder ? 

     App_Start  

28. RouteConfig.cs file is under in which App folder ?

     App_Start 

29. WebApiConfig.cs file is under in which App folder ?

     App_Start 

30. How to format Date in Razor View using ASP.Net MVC? 

       @string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(Html.DisplayFor(modelitem => item.Start_Date).ToString())) 

Best of luck :)




Comments

Popular posts from this blog

OOP Concept with Real Time Examples

A design philosophy is OOP. Object Oriented Programming is what it stands for. In contrast to outdated procedural programming languages, object-oriented programming (OOP) employs a separate set of programming languages. In OOP, everything is categorised as self-sustaining "objects". As a result, you achieve re-usability using the four core concepts of object-oriented programming. Programmes are organised around objects and data rather than action and logic in the object-oriented programming (OOP) paradigm.    Let's use your "Leg" as an example to grasp the object orientation clearly. The class "Leg" is one. Left and right legs are objects of type Leg on your body. A series of electrical impulses supplied through your body parts (through an interface) are what manage or control their primary functions. As a result, the body part serves as an interface between your body and your legs. The Leg is a well-designed class. The attributes of the Leg are m

Windows Application Development - Dotnet Environment Basic understandings

The development life cycle for creating Windows desktop applications using the .NET framework typically involves several stages. Here's an overview of the typical life cycle: Requirement Analysis: Gather and analyze the requirements for the Windows application. Understand the business needs, user expectations, features, and functionalities that the application should have. Design: Create a design for your application's user interface (UI) and overall architecture. Decide on the layout, controls, navigation flow, and other visual aspects. Plan the data storage mechanisms, database schema, and integration with other systems if necessary. Development: Begin coding the application using the .NET framework. Use programming languages like C# or VB.NET. Create classes, forms, controls, and implement the business logic. You'll work on creating the UI, handling user interactions, data processing, and any required integrations. Testing: Thoroughly test the applicatio

What is difference between abstract class and interface and when should we use interface and abstract class?

Although you can generate derivatives from this, you cannot create an object of the abstract class. Either abstract or non-abstract methods can be found in an abstract class. There is no implementation for abstract members in the abstract class; nevertheless, a derived class must supply one. Both abstract and non-abstract members can be found in an abstract class. The members of an interface, however, must all override the members of its derived class because all interface elements are implicitly abstract in nature. Similar to defining an interface, declaring an abstract class includes all of its abstract members. Specifically, we can say that an interface is a class that has all abstract members. Classes can only descend from one base class, therefore if you wish to use abstract classes to give a bunch of classes polymorphism, they must all all descend from that base class. Members that have already been put into practise may also be offered by abstract classes. With an abstract class