Sunday, 8 January 2017

Interviews Questions - MVC

  • Difference between ASP.NET WebForms and ASP.NET MVC

Difference between ASP.NET MVC and WebForms
Asp.Net Web Forms
Asp.Net MVC
Asp.Net Web Form follow a traditional event-driven development model.
Asp.Net MVC is a lightweight and follows MVC (Model, View, Controller) pattern based development, model.
Asp.Net Web Form has server controls.
Asp.Net MVC has HTML helpers.
Asp.Net Web Form supports view state for state management at the client side.
Asp.Net MVC does not support view state.
Asp.Net Web Form has file-based URLs means file name exist in the URLs must have its physical existence.
Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
Asp.Net Web Form follows Web Forms Syntax
Asp.Net MVC follow customizable syntax (Razor as default)
In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
In Asp.Net MVC, Views and logic are kept separately.
Asp.Net Web Form has Master Pages for a consistent look and feels.
Asp.Net MVC has Layouts for a consistent look and feels.
Asp.Net Web Form has User Controls for code re-usability.
Asp.Net MVC has Partial Views for code re-usability.
Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.
Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Hence it is best for developing an interactive web application with the latest web standards.
Asp.Net Web Form is not Open Source.
Asp.Net Web MVC is an Open Source.
  • What is MVC?
MVC (Model-View-Controller) is an architectural pattern that separates an application into three main logical components: I)Model II)VIEW III)Controller.

I) Model: In MVC the Model component corresponds to all the data related logic. This can represent either the data that is being transferred between the View and Controller components or any other business logic related data.

II) View: In MVC View component is used for all the User Interface (UI) logic of the application. It is use to render a data (format the data) in the way that we want to present to the end users like underline it, bold it, table format it etc.

III) Controller: In MVC Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output.
  • What is ViewResult()?
ViewResult is automatically inherit from ActionResult class. ActionResult is base type while ViewResult is sub type of ActionResult. When you set Action's return type ActionResult, you can return any subtype of it e.g JsonResult, PartialView, View, RedirectToAction. But when you use subtype like ViewResult you are bounding your action that it will only return subtype as result
  1. The View() method doesn't make new requests, it just renders the view without changing URLs in the browser's address bar. 

  1. The RedirectToAction() method makes new requests and URL in the browser's address bar is updated with the generated URL by MVC. 

  1. The Redirect() method also makes new requests and URL in the browser's address bar is updated, but you have to specify the full URL to redirect 

  1. Between RedirectToAction() and Redirect() methods, best practice is to use RedirectToAction() for anything dealing with your application actions/controllers. If you use Redirect() and provide the URL, you'll need to modify those URLs manually when you change the route table. 

  1. RedirectToRoute() redirects to a specific route defined in the Route table. 

  • What is ViewBag and ViewData in MVC?
ViewBag and ViewData is a mechanism to pass data from controller to view.
(Please Note: To pass data from controller to view, it’s always good practice to use strongly typed view models over ViewBag and ViewData, because it provide compile time error checking.)
I) ViewData: ViewData is dictionary of objects that are stores and retrieve using strings as keys.
ViewData[“YourKey”] = “Some Data”;
ViewBag.YourProperty = “Some Data”;
II) ViewBag: ViewBag uses dynamic features that are introduced in C# 4. It allows an object to have properties dynamically added to it.
Both ViewBag and ViewData not provide compile time error. Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
  • How URL maps in WebForms And MVC?
In WebForms URL are mapped to physical files like "http://localhost/WebForm1.aspx"
In MVC URLs are mapped to controller action methods like "http://localhost/Home/Index"
  • How we can switch between C# code and HTML code?
To switch between csharp and HTML code in MVC razor view engine syntax, we uses @ symbol. Use @{ } to define a code block. If we want to define some variables and perform calculations, then use code block. Use @* *@ to comment in razor views
@*This is a comment
in razor views*@
@ symbol is used as code delimiter in razor views. However, razor is smart enough to recognize the format of internet email address and not to treat the @ symbol as a code delimiter.
This is my email address<br />
<b>ghazisb@testmail.com</b>
result:
This is my email address
ghazisb@testmail.com

Use @ symbol to escape @
I will meet you @@ home
result:

I will meet you @ home
  • What is FormCollection?
FormCollection automatically receive all posted data in MVC.
  • What is UpdateModel() and TryUpdateModel() in MVC?
UpdateModel() and TryUpdateModel() both are use to update form values and perform validation on it.
  • What is the difference between UpdateModel() and TryUpdateModel()?
UpdateModel() throws an exception if validation fails, where as TryUpdateModel() will never throw an exception.
  • Is it mandatory to use "UpdateModel()" or "TryUpdateModel()" function to update the Model?
No, It's not necessary to use both of these function to update the Model.
  • What is White List and Black List in MVC?
White List: White List is a list of all the attributes of a Model to Include in during Model updating in MVC.

Black List: Black List is a list of all the attributes of a Model to Exclude from the Model  during updating the Model in MVC.
  • How many ways to "Include" (White List) the attributes 
    during Model updating in MVC?
There are many ways to Include the attributes during Model updating in MVC, like,

i) By using TryUpdateModel() or UpdateModel()
        // Post: /Employee/ 
        [ActionName("EmployeesGetByID")]
        [HttpPost]
        public ActionResult EmployeesGetByID_Post(int ID)
        {
            Employee employee = new Employee();
            EmployeeBLL employeeBLL = new EmployeeBLL();
            employee = employeeBLL.EmployeeGetByID(ID);
            TryUpdateModel(employee, new string[] { "ID", "Gender", "City", "DeptID" });
            //or
            //UpdateModel(employee, new string[] { "ID", "Gender", "City", "DepartmentID" });
           
            if (ModelState.IsValid)
            {
                employeeBLL.EmployeeUpdate(employee);               
            }
            return RedirectToAction("Index");
        }

ii) Use Bind attribute in method paramter
[ActionName("EmployeesGetByID")]
[HttpPost]
public ActionResult EmployeesGetByID_Post([Bind(Include = "ID, City, Gender, DeptID")] Employee employee)
        {   
            EmployeeBLL employeeBLL = new EmployeeBLL();
     Employee employee = new Employee();
            employee.Name = employeeBLL.EmployeeGetByID(employee.ID).Name;
            TryUpdateModel(employee, new string[] { "ID", "Gender", "City", "DepartmentID" });           

            if (ModelState.IsValid)
            {
                employeeBLL.EmployeeUpdate(employee);
            }
            return RedirectToAction("Index");
        }

iii) Using Interface
     public interface IEmployee
    {
        int ID { getset; }
        string City { getset; }
        string Gender { getset; }
        int? DepartmentID { getset; }
        int? DeptID { getset; }
    }
       [ActionName("EmployeesGetByID")]
        [HttpPost]
        public ActionResult EmployeesGetByID_Post(int ID)
        {
            Employee employee = new Employee();

            EmployeeBLL employeeBLL = new EmployeeBLL();

            employee = employeeBLL.EmployeeGetByID(ID); 
            TryUpdateModel<IEmployee>(employee);
            //or
            //UpdateModel<IEmployee>(employee);

            if (ModelState.IsValid)
            {
                employeeBLL.EmployeeUpdate(employee);
            }
            return RedirectToAction("Index");
        } 
  • How many ways to "Exclude" (Black List) the attributes 
    during Model updating in MVC?
There are many ways to Exclude the attributes during Model updating in MVC, like,

i) By using TryUpdateModel() or UpdateModel()
        // Post: /Employee/ 
        [ActionName("EmployeesGetByID")]
        [HttpPost]
        public ActionResult EmployeesGetByID_Post(int ID)
        {
            Employee employee = new Employee();
            EmployeeBLL employeeBLL = new EmployeeBLL();
            employee = employeeBLL.EmployeeGetByID(ID);
            TryUpdateModel(employee, null, null, new string[] { "ID", "Gender", "City", "DeptID" });
            //or
            //UpdateModel(employee, null, null, new string[] { "ID", "Gender", "City", "DepartmentID" });
           
            if (ModelState.IsValid)
            {
                employeeBLL.EmployeeUpdate(employee);               
            }
            return RedirectToAction("Index");
        }
ii) Use Bind attribute in method paramter
[ActionName("EmployeesGetByID")]
[HttpPost]
public ActionResult EmployeesGetByID_Post([Bind(Exclude = "Name")] Employee employee)
        {   
            EmployeeBLL employeeBLL = new EmployeeBLL();
     Employee employee = new Employee();
            employee.Name = employeeBLL.EmployeeGetByID(employee.ID).Name;
            TryUpdateModel(employee, new string[] { "ID""Gender""City""DepartmentID" });           

            if (ModelState.IsValid)
            {
                employeeBLL.EmployeeUpdate(employee);
            }
            return RedirectToAction("Index");
        }
iii) Using Interface
     public interface IEmployee
    {
        int ID { getset; }
        string City { getset; }
        string Gender { getset; }
        int? DepartmentID { getset; }
        int? DeptID { getset; }
    }
       [ActionName("EmployeesGetByID")]
        [HttpPost]
        public ActionResult EmployeesGetByID_Post(int ID)
        {
            Employee employee = new Employee();
            EmployeeBLL employeeBLL = new EmployeeBLL();
            employee = employeeBLL.EmployeeGetByID(ID);
            TryUpdateModel<IEmployee>(employee);
            //or
            //UpdateModel<IEmployee>(employee);
            if (ModelState.IsValid)
            {
                employeeBLL.EmployeeUpdate(employee);
            }
            return RedirectToAction("Index");
        }
  • What is ViewEngine in MVC?
View Engine is responsible for rendering the view into html form to the client (browser). By default, ASP.NET MVC support Web Form(ASPX) and Razor View Engine. There are many third party view engines (like Spark, Nhaml etc.) that are also available for ASP.NET MVC.
  • What is the difference between ASPX and RAZOR view engines?
Following are some difference between ASPX and RAZOR view engines:

I) Entry with ASP.NET MVC (ASPX and Razor View Engine)                   
   o  ASPX View Engine is the default view engine for the ASP.NET MVC that is included            with ASP.NET MVC from the beginning.
   o  Razor View Engine is an advanced view engine and introduced with MVC3. This is not        a language but it is a markup syntax.

Entry with ASP.NET MVC (ASPX and Razor View Engine)

II) MasterPage /Layout
   o In ASPX View Engine we use masterPages.
   o In Razor View Engine we use Layouts.
MasterPage /Layout

III) WebUserControl /PartialPage
   o In ASPX View Engine we use WebUserControls.   
   o In Razor View Engine we use PartialPage.
PartialPage /WebUserControl

IV) Extension
   o ASPX View Engine has a similar extension as in a simple web application like .aspx for       the views, .ascx for UserControls and .master for Master Pages.
   o Razor View Engine has .cshtml (with C#) and .vbhtml (with VB) extension for views,          Layout and Partial views.
Extension

V) Syntax
   o ‘<%:’ delimiters use as starting point and ‘ %>’ use as ending point. You can write the        code between them in ASPX Engine.
      <%: Html.ActionLink("Login ", " LoginView ") %>
   o ‘@’ symbol uses in Razor Engine to write the code. 
     @Html.ActionLink("Login", "LoginView")
Syntax



VI) Namespace
   o ASPX View Engine supports System.Web.Mvc.WebFormViewEngine.
   o Razor View Engine supports System.Web.Razor.

VII) Performance
   o Aspx Engine is faster compared to Razor Engine.
   o Razor Engine is a little slow compared to Aspx Engine.

VIII) Cross-Site Scripting Attacks
   o Razor Engine prevents Cross-Site Scripting Attacks, in other words it encodes the               script or HTML tags like <,> before rendering to view.
   o ASPX Engine does not prevent Cross-Site Scripting Attacks, in other words any script           saved in the database will be fired while rendering the page.

The main difference between ASXP and RAZOR view engines is syntax. Otherwise there are no major differences between these two. In ASPX view engine, the server side script is wrapped between <% %>, where as in RAZOR we use @. However, it is very easy to switch between HTML and Code using RAZOR views.
Depending on the programming language you have chosen, RAZOR views have the extension of .CSHTML (when we use C# as programming language) or .VBHTML (when we use  VB as programming language) , whereas ASPX views has the extension of .ASPX. For class type files .CS is the extension in case of programming language is C# and .VB is the extension for class type files in case of programming language is VB.
  • Is it possible, to have both ASPX and RAZOR views in one application?
Yes, it’s possible. When we right click on any controller action method, and select "Add View" from the context menu, we shall have the option to choose the view engine of our choice from the "Add View" dialog box either it is aspx or razor.
  • Is it possible, to use a third party view engine with asp.net MVC?
Yes, it’s possible to use third party view engines and it's very easy to include third party view engine as well.
  • How does a controller find a view in MVC?
Controller looks for a view with the same name as that of the controller action method in MVC in the following locations
A. Views/Shared
B. Views/FolderNameMatchingControllerName

View extension can be any of the following
I).cshtml (C#)
II).vbhtml (VB)
III).aspx
IV).ascx

If we have all of the following files in "Views/Customer" folder, then MVC picks up "Index.aspx"
I) Index.aspx
II) Index.cshtml
III) Index.vbhtml
IV) Index.ascx
If you want to use "Index.cshtml" instead, then specify the full path as shown below.
public ActionResult Index()
{
    return View("~/Views/Customer/Index.cshtml");
}
If you specify only the name of the view along with it's extension as shown below, you will get an error.
return View("Index.cshtml", employees.ToList());

If you want to use a view name which is not inside the views folder of the current controller, then specify the full path as shown below.
public ActionResult Index()
{
    return View("~/Views/Home/Index.aspx");
}
Please note that
I. MVC is all about convention over configuration
II. Views folder contains one folder for each controller and a "Shared" folder
III. Shared folder is used to store views shared between controllers. Master and Layout pages are stored in "Shared" folder.
  • What is HTML helper?
HTML helper is a method that is used to render HTML content in a View. HTML helpers are implemented as extension methods.
For example, to produce the HTML for a textbox with id="City" and name="City", we can type all the html in the view as shown below

<input type="text" name="City" id="City" />
OR
We can use the "TextBox" html helper.
@Html.TextBox("City")

There are several overloaded versions. To set a value, along with the name, use the following overloaded version.
@Html.TextBox("City", "London")

The above html helper, generates the following HTML
<input id="City" name="City" type="text" value="London" />

To set HTML attributes, use the following overloaded version. Notice that, we are passing HTML attributes (style & title) as an anonymous type.
@Html.TextBox("City", "London", new { style = "background-color:Pink; color:Green; font-weight:bold", title="Please enter your first name" })

Some of the html attributes, are reserved keywords. Examples include class, readonly etc. To use these attributes, use "@" symbol as shown below.
@Html.TextBox("City""London"new { @class = "blueText", @readonly="true" })

To generate a label for "City Name"
@Html.Label("City""City Name)
To generate a textbox to enter password, so that the input is masked
@Html.Password("Password")
To generate a multi-line textbox with 4 rows and 12 columns
@Html.TextArea("Comments""", 4, 12, null)
To generate a hidden textbox
@Html.Hidden("id")
Hidden textbox is used to store id values. Id values are not displayed on the page to the end user, but we need them to update data when the form is posted to the server.
  • Is it possible to create our own custom html helpers?
Yes, it is possible to create our own custom html helpers.
  • Is it mandatory to use HTML helpers?
No, you can type the required HTML, but using HTML helpers will greatly reduce the amount of HTML that we have to write in a view. Views should be as simple as possible. All the complicated logic to generate a control can be encapsulated into the helper, to keep views simple.
  • What is @Html.TextBox() and @Html.TextBoxFor()?
A:  @Html.TextBox("FirstName")
B:  @Html.TextBoxFor(m => m.FirstName)
will both produce text input type like
<input id="FirstName" name="FirstName" type="text" />
  • What is the difference between @Html.TextBox() and @Html.TextBoxFor()?
@Html.TextBox() is not strongly type whereas @Html.TextBoxFor() is strongly type. Ultimately they both produce the same HTML.

A:  @Html.TextBox("FirstName")
B:  @Html.TextBoxFor(m => m.FirstName)
will both produce
<input id="FirstName" name="FirstName" type="text" />
So what does that mean in terms of use?
Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.
It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
  • What is the difference between @Html.Dropdown() and @Html.DropdownFor()?
@Html.Dropdown() is not strongly type whereas @Html.DropdownFor() is strongly type. Ultimately they both produce the same HTML (Dropdownlist).
  • What is the purpose of DisplayName, DisplayFormat, ScaffoldColumn, DataType, DisplayColumn and UIHint Attributes in ASP.NET MVC?
A.DisplayName: If you want "FirstName" property of a class to be displayed as "First Name" in viewuse DisplayAttribute or DisplayName attribute. DisplayName attribute is in System.ComponentModel namespace.
B.DisplayFormat: DisplayFormat is used to format the string of a particular attribute of a class like to format the DateTime.
C.ScaffoldColumn: ScaffoldColumn attribute is used to display or hide particular attribute of a class. Like if we want to hide Salary attribute of a class from the view, we set [ScaffoldColumn(false)] on Salary column. Please note that, ScaffoldColumn is only work with @Html.DisplayForModel().
D.DataType: When you want to display a column with specific type like currency symbol, display value as email type or as url use DataType attribute on the top of the property.
E.DisplayColumn: When you want to display a single column from whole model, use DisplayColumn attribute on Model level. Like we want to display only FirstName on view use [DisplayColumn("FirstName")] on Model level.
F.UIHint: UIHint("NameOfView") attribute is used to specify the name of the template to use to display the data field.
Example:
[MetadataType(typeof(EmployeeMetaData))]
 //[DisplayColumn("FirstName")]
//If we set [DisplayColumn("FirstName")] here, only FirstName will be render on view
    public partial class Employee
    {

    }
    public class EmployeeMetaData
    {
        //If you want "First Name" to be displayed as "First Name",
        //use DisplayAttribute or DisplayName attribute.
        //DisplayName attribute is in System.ComponentModel namespace.
        //[DisplayAttribute(Name="First Name")]
        //[Display(Name = "First Name")]
        [DisplayName("First Name")]

        public string First Name { get; set; }

       // Display only Time Part
       // [DataType(DataType.Time)]
       // Display only Date Part

        //To get only the date part in a datetime data type

        //[DisplayFormat(DataFormatString = "{0:d}")]

        //[DisplayFormatAttribute(DataFormatString="{0:d}")]

        //To get time in 24 hour notation

        //[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}")]

        //To get time in 12 hour notation with AM PM

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]

        public DateTime? HireDate { get; set; }

        // If gender is NULL, "Gender not specified" text will be displayed.

        [DisplayFormat(NullDisplayText = "Gender not specified")]

        public string Gender { get; set; }

        //If you don't want to display a column use ScaffoldColumn(false) attribute.

        //This only works when you use @Html.DisplayForModel() helper
        // Display currency symbol. For country specific currency, set 
         // culture using globalization element in web.config. 
        // For Great Britain Pound symbol
        // <globalization culture="en-gb"/>

        //[ScaffoldColumn(false)]
         [DataType(DataType.Currency)]
         public int? Salary { get; set; }
        //Display mailto hyperlink
        DataType.EmailAddress)]

        public string EmailAddress { get; set; }
     //The following is the convention used by MVC to find the customized templates
  //1. The customized display templates must be in a sub-folder that is named -    //DisplayTemplates. Editor templates must be in a sub-folder that is named -    //EditorTemplates.
  //2. These sub-folders can live in "Shared" folder, or a specific views folder. If these    //folders are present in the Shared folder, then the templates are available for all the    //views. If they are in a specific views folder, then, they are available only for that set of   //views.
//3. The name of the template must match the name of the type. For example, as we are //customizing DataType.Url template, the name of the template in this case has to be    //Url.cshtml or Url.ascx.
//[UIHint("MyOpenNewWindow")]
    [DataType(DataType.Url)
    public string PersonalyWebSite { get; set; }

    }
  • What is @Html.Display("Data"), @Html.DisplayFor(model => model), @Html.DisplayForModel()?
All of these are also called templated helpers in MVC. These all were introduced in MVC2. These built in templated helpers can be broadly classified into 2 categories.
1. Display Templates
2. Editor Templates
There are 3 DISPLAY templated helpers
@Html.Display("Data") - This template is used for views that are not strongly type. For example, if you have stored data in ViewData, then we can use this templated helper using the key that was used to store data in ViewData.
@Html.DisplayFor(model => model) - It is used with strongly typed views. If your model has properties that return complex objects, then this templated helper is very useful.
@Html.DisplayForModel() - Used with strongly typed views. Walks thru each property, in the model to display the object. 
Along the same lines, there are 3 EDIT templated helpers
@Html.Editor("EmployeeData")
@Html.EditorFor(model => model)
@Html.EditorForModel()
  • What is the purpose of using @Url.Content()?
@Url.Content converts a virtual (relative) path to an application absolute path. It means when you wish to resolve a url for any file or resource on your site and you would pass it the relative path, like,
@Url.Content("~/yourPath/File.html")or
<img src="@Url.Content(@Model.Image)" alt="@Model.AlternateText" />
  • What is the purpose of using @Url.Action()?
@Url.Action() is used to resolve an action from a controller like:
@Url.Action("YourActionName", "YourControllerName", new { yourVariable = yourValue })
  • What is HTML encoding?
HTML encoding is the process of replacing ASCII characters with their 'HTML Entity' equivalents. For example replacing
html encoding 
  • Why would we html encode?
In MVC, to avoid cross site scripting attacks, all output is automatically html encoded.
  • How to detect Errors in MVC Views at Compile Time?
If you want to enable compile time error checking for views in MVC
1. Open MVC project file using a notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.
  • What is Partial View in ASP.NET MVC?
Partial View is similar to web user controls in ASP.NET Web form. When we make view as partial, then we can use it in many other main views by just invoking them.
  • What does @Html.Partial() in ASP.NET MVC?
It is use to render a partial view on your main view by just invoking them with following piece of code @Html.Partial("_PartialViewName", objName).
  • What is @Html.RenderPartial() in ASP.NET MVC?
@Html.RenderPartial() is also use for rendering partial views.
  • What is the difference between Partial() and RenderPartial()?
I. The return type of "RenderPartial" is void, where as "Partial" returns "MvcHtmlString"
II. Syntax for invoking Partial() and RenderPartial() methods in Razor views
@Html.Partial("PartialViewName") and { Html.RenderPartial("PartialViewName");  }
III. Syntax for invoking Partial() and RenderPartial() methods in webform views
<%: Html.Partial("PartialViewName") %>
<% Html.RenderPartial("PartialViewName"); %>
  • When would you use RenderPartial() over Partial() and vice versa?
The main difference is that "RenderPartial()" returns void and the output will be written directly to the output stream, where as the "Partial()" method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().
  • Which one is better for performance?
From a performance perspective, rendering directly to the output stream is better. RenderPartial() does exactly the same thing and is better for performance over Partial().
  • What are T4 templates and their purpose?
T4 stands for Text Template Transformation Toolkit and are used by visual studio to generate code when you add a view or a controller.
  • Where does these T4 templates live?
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\[CSharp | FSharp | VisualBasic]\Web\[MVC 2 | MVC 3 | MVC 4]\CodeTemplates 
What is the file extension for T4 templates?
 The file extension for T4 templates is ".tt".
  • Is it possible to customize T4 templates?
Yes, T4 templates can be customized in place, if you want the customized T4 templates available for all MVC projects on that machine.
If you want to customize T4 templates, only for a specific project, then copy "CodeTemplates" folder and paste it in the root directory of your MVC project. Right click on the template files(with .tt extension), and select Properties and delete "TextTemplatingFileGenerator".  By deleting this from CustomTool property, we are telling visual studio not to run them during the build. They will be manually called when we add a view or a controller using "Add View" and "Add Controller" dialog box.
  • Is it possible to add your own T4 template to the existing list of templates?
Absolutely, simply create a file with ".tt" file extension in "AddController" folder in "CodeTemplates". If it is for adding a view, then put it in "AspxCSharp"(if view engine is aspx) or "CSHTML"(if view engine is razor) folder.
  • What is Cross-site scripting attack in Web Applications?
Cross-site scripting attack are also called as XSS attack, is a security weakness found in Web applications. Cross-site Scripting (XSS) refers to client-side code injection attack in which an attacker can execute malicious scripts into a web site. XSS allows hackers to inject client-side script into Web pages, and later, if that web page is viewed by others, the stored script gets executed. The concerns of XSS may range from a minor trouble like displaying an alert() box to a significant security risk, like stealing session cookies means login with to any system without interning user name or/and password.
  • What is @Html.Raw() method in ASP.NET MVC?
@Html.Raw() Return markup that is not HTML encoded. For example if following text is stored in our database, "This player is <b><u>very good</u></b>" and we want to display this message as "This player is very good" on our view, we use @Html.Raw(item.MyMessage) htlm helper. If we not use @Html.Raw() html helper, the end result will be "This player is <b><u>very good</u></b>". Note to save this type of text we should must use [ValidateInput(false)] on controller action method of saving. It will allow user to save HTML code to DB as well other wise we get an exception during run time to save HTML to DB.
  • What is Layout. How they can be used and the advantage of using Layout view?
Layout views provide the advantage of maintaining consistent look and feel across all the views in an mvc application. It is simillar to master pages in web forms applications. A typical layout view consists of
1. Header
2. Footer
3. Navigation menu
4. View specific content
use following line of code just below, @model declaration
@{
    ViewBag.Title = "Employee List Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
Points to note:
I. View specific title is retrieved using @ViewBag.Title.
II. View specific content will be plugged-in at the location, where RenderBody() function is called.
  • What is _ViewStart.cshtml file?
ASP.NET MVC 3, has introduced _ViewStart.cshtml. Specify the Layout property in this file and place it in the Views folder. All the views will then use the layout file that is specified in _ViewStart.cshtml. This eliminates the need to specify Layout property on each and every view, and making them more cleaner and maintainable. Please note that this view must be named as _ViewStart.cshtml.
  • What is the purpose of using PartialViewResult as return type in controller action method?
It's used to return a partial view and restrict the view not to use lay outs files  (like _Layout.cshtml). Use following piece of code for this purpose PartialView("_PartialViewName", objName).
  • How to define section in view?
To define a section in view, use @section followed by, the name of the section. For example if we define a menu using section which is going to display List, Details and Delete links use following piece of code.
@section myMenu
{
    @Html.ActionLink("List""Index"<br />
    @Html.ActionLink("Details""Details"new { id = Model.Id }) <br />
    @Html.ActionLink("Delete""Delete"new { id = Model.Id })

}
  • How to check that section is defined or not?
We can check whether or not particular section is defined or not with following piece of code;
@if (IsSectionDefined("myMenu"))
    {
        @RenderSection("myMenu", false)
    }
    else
    {
        @Html.ActionLink("Student List", "Index")

    }
  • What is  Action selectors in MVC?
Actions are public methods in a MVC controller that replies to a URL request. You can control or stimulus which action method gets invoked using action selectors in MVC. Action selectors are attributes that can be applied to an action method in a controller.
  • What is ActionName Selector in MVC?
This action selector is used when you want to invoke an action method with a different name.
For example, the following URL request would invoke Index() action method in EmployeeController.
/Employee/Index
public class EmployeeController : Controller
{
    public string Index()

    {
        return "Index action method invoked";

    }
}

If you want to invoke Index() action method, with the following URL
/Employee/List
Then decorate the action method with ActionName attribute as shown below.
public class EmployeeController Controller
{
    [ActionName("List")]

    
public string Index()
    {
        
return "Index action method invoked";
    }
}

Now, if you navigate to /Employee/Index, you will get an error - The resource cannot be found.
At the moment, the Index() action method is returning a string, but if it returns a view, should the view be named - Index or List.?
[ActionName("List")]
public ActionResult Index()
{
    return View();

}

List should be the view name. If for some reason, you want to use "Index" as the view name, then modify the controller action method as shown below.
[ActionName("List")]
public ActionResult Index()
{
    return View("Index");

}

  • What is AcceptVerbs Selector in MVC?
Use this selector, when you want to control, the invocation of an action method based on the request type. In the example below, the "Edit" method that is decorated with GET acceptverb responds to the GET request, whereas the other "Edit" method responds to POST request. The default is GET. So, if you don't decorate an action method with any accept verb, then, by default, the method responds to GET request.
public class HomeController Controller
{
    [AcceptVerbs(HttpVerbs.Get)]

    public ActionResult Edit(int id)

    {
        Employee objEmployee = GetEmployeeDataFromDB(id);

        return View(employee);

    }
    
    [AcceptVerbs(HttpVerbs.Post)]

    
public ActionResult Edit(Employee employee)
    {
        if (ModelState.IsValid)

        {
            // Save employee to the database

            return RedirectToAction("Index");

        }
        return View(employee);

    }
}


HttpGet and HttpPost attributes can be used as shown below. This is an alternative to using AcceptVerbs attribute.
public class HomeController Controller
{
    [HttpGet]

    
public ActionResult Edit(int id)
    {
        Employee employee = GetEmployeeFromDB(id);

        return View(employee);

    }
    
    [HttpPost]

    
public ActionResult Save(Employee employee)
    {
        if (ModelState.IsValid)

        {
            // Save employee to the database

            return RedirectToAction("Index");

        }
        return View(employee);

    }
}
  • What is the use of NonAction attribute in MVC? OR How do you restrict access to public methods in a controller?
An action method is a public method in a controller that can be invoked using a URL. So, by default, if you have any public method in a controller then it can be invoked using a URL request. To restrict access to public methods in a controller, NonAction attribute can be used.
[NonAction]
public string NoAccesAction()
{
    return " NoAccesAction method is invoked Invoked";

}

Now, if you naviage to URL /ControllerName/NoAccesAction, you will get an error - The resource cannot be found.
Another way to restrict access to methods in a controller, is by making them private. 
private string NoAccesAction()
{
     return "NoAccesAction method is invoked Invoked";

}

In general, it's a bad design to have a public method in a controller that is not an action method. If you have any such method for performing business calculations, it should be somewhere in the model and not in the controller. However, if for some reason, if you want to have public methods in a controller and you don't want to treat them as actions, then use NonAction attribute.
  • What are action filters in asp.net MVC?
Action filters are attributes that can be applied either on a controller action method or on a controller. When applied at the controller level, they are applicable for all actions within that controller. Action filters allow us to add, pre and post processing logic to an action method. This means, they allow us to modify the way in which an action is executed.
  • Can you create a custom action filter in MVC?
Yes, It is possible to create custom action filter in MVC.
  • Name a few action filters in MVC?
1) Authorize.
2) ChildActionOnly.
3) HandleError.
4) OutputCache.
5) RequireHttps.
6) ValidateInput.
7) ValidateAntiForgeryToken.
  • What is ChildActionOnly Attribute in MVC?
1. Any action method that is decorated with [ChildActionOnly] attribute is a child action method.
// This method is accessible only by a child request. A runtime
// exception will be thrown if a URL request is made to this method
[ChildActionOnly]
public ActionResult Countries(List<String> countryData)
{
return View(countryData);
}
2. Child action methods will not respond to URL requests. If an attempt is made, a runtime error will be thrown stating - Child action is accessible only by a child request.
3. Child action methods can be invoked by making child request from a view using "Action()" and "RenderAction()" html helpers.
 @Html.Action("Countries", new { countryData = new List<string>() { "Pak", "UK", "UAE" } })
                OR
  @{
    Html.RenderAction("Countries", new { countryData = new List<string>() { "Pak", "UK", "UAE" }});
     }
4. An action method doesn’t need to have [ChildActionOnly] attribute to be used as a child action, but use this attribute to prevent if you want to prevent the action method from being invoked as a result of a user request.
5. Child actions are typically associated with partial views, although this is not compulsory.
6. Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked using Action() or RenderAction() helpers.
7. Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods.
  • What is OutputCache attribute in MVC?
OutputCacheAttribute is used to cache the content returned by a controller action method, so that, the same content does not need to be generated each and every time the same controller action is invoked.
//Here, we are using OutPutCache attribute to cache the content returned by Message() action method for 10 seconds.
[OutputCache(Duration = 10)]
public ActionResult Message()
{
System.Threading.Thread.Sleep(3000);
return View();
} 
  • What is CacheProfiles in MVC?
To cache the data returned by Index() action method, for 40 seconds, we would use [OutputCache] attribute as shown below.
[OutputCache(Duration = 40)]
public ActionResult Index()
{
return View(db.Employees.ToList());

}

This approach having following disadvantages:
1. Later, if we have to change these cache settings, then we need to change them at several places. Maintaining the code becomes complicated. Also, changing the application code requires build and re-deployment.
2.If you have to apply the same cache settings, to several methods, then the code needs to be duplicated.
To overcome these disadvantages, cache settings can be specified in web.config file using cache profiles.
Step 1: Specify cache settings in web.config using cache profiles
<system.web>
  <caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <clear/>
     <add name="CacheDuration" duration="40" varyByParam="none"/>
     </outputCacheProfiles>
   </outputCacheSettings>
  </caching>
</system.web>
And can be used in the following way;
[OutputCache(CacheProfile = "CacheDuration")]
public ActionResult Index()
{
  return View(dbObj.Students.ToList());
}
The cache settings are now read from one central location i.e from the web.config file.
  • What is RequireHttps attribute in MVC?
[RequireHttps] attribute forces an unsecured HTTP request to be re-sent over HTTPS. 
[RequireHttps]
public string Login()
{
  return "This method should be accessed only using HTTPS protocol";
}
RequireHttps attribute can be applied on a controller as well. In this case, it is applicable for all action methods with in that controller.
  • What is ValidateInput attribute in MVC?
In ASP.NET MVC, by request validation is enabled. This attribute is used to enable or disable request validation.
Example:
Controller action method code;
[HttpPost]
public string Index(string comments)
{
  return "Your Comments: " + comments;
}
View;
<div style="font-family:Arial">
@using (Html.BeginForm())
{
 <b>Comments:</b>
 <br />
 @Html.TextArea("comments")
 <br />
 <br />
 <input type="submit" value="Submit" />
}
</div>
When you type following text in the "Comments" textbox and click "Submit".
<b>Hello World</b>
You will get an error messaging saying - A potentially dangerous Request.Form value was detected from the client (comments="<b>Hello World</b>"). This is because, by default, request validation is turned on in ASP.NET MVC and does not allow you to submit any HTML, to prevent XSS (Cross site scripting attacks). 
If you want the user to be able to submit HTML tags like <b>, <u>, <h1> etc. For this to happen, we need to turn off request validation, by decorating the action method with ValidateInput attribute as shown below.
[HttpPost]
[ValidateInput(false)]
public string Index(string myInput)
{
 return "Your Entered: " + myInput;
}
  • What is Custom Action Filters in ASP.NET MVC?
In any scenario where we want to log some details before or after an action of a controller is called. To fulfill this requirement ASP.NET MVC comes up with four different Action Filters. These actions filters are Authorization filters, Action filters, Result filters and Exception filter (whenever an exception is thrown) for executing filtering logic either pre-or post-execution of an action method of a controller. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.
//Example:
//In following example we’re using two custom filters ActionFilterAttribute and IExceptionFilter
//Custom Filter class
using System;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace MVCDemoApp
{
    public class TrackActionExecution : ActionFilterAttribute, IExceptionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string message = "\n" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName +
                " -> " + filterContext.ActionDescriptor.ActionName + " -> OnActionExecuting \t- " +
                DateTime.Now.ToString() + "\n";
            LogExecutionTime(message);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string message = "\n" + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName +
                " -> " + filterContext.ActionDescriptor.ActionName + " -> OnActionExecuted \t- " +
                DateTime.Now.ToString() + "\n";
            LogExecutionTime(message);
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            string message = filterContext.RouteData.Values["controller"].ToString() +
                " -> " + filterContext.RouteData.Values["action"].ToString() +
                " -> OnResultExecuting \t- " + DateTime.Now.ToString() + "\n";
            LogExecutionTime(message);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            string message = filterContext.RouteData.Values["controller"].ToString() +
                " -> " + filterContext.RouteData.Values["action"].ToString() +
                " -> OnResultExecuted \t- " + DateTime.Now.ToString() + "\n";
            LogExecutionTime(message);
            LogExecutionTime("---------------------------------------------------------\n");
        }

        public void OnException(ExceptionContext filterContext)
        {
            string message = filterContext.RouteData.Values["controller"].ToString() + " -> " +
               filterContext.RouteData.Values["action"].ToString() + " -> " +
               filterContext.Exception.Message + " \t- " + DateTime.Now.ToString() + "\n";
            LogExecutionTime(message);
            LogExecutionTime("---------------------------------------------------------\n");
        }

        private void LogExecutionTime(string message)
        {
            File.AppendAllText(HttpContext.Current.Server.MapPath("~/Data/Data.txt"), message);
        }
    }
}
//Controller code
//Controller calling methods (actions) with having custom filter implemented
public class HomeController : Controller
{
    [TrackActionExecution]

    public string Index()

    {
        return "My Index Action Invoked";

    }

    [TrackActionExecution]

    public string Welcome()

    {
        throw new Exception("Exception ocuured");

    }
}

  • What are different types of ActionResults in ASP.NET MVC?
ActionResult is an abstract class and has several sub types. These sub types are ViewResult, PartialViewResult, JsonResult, RedirectResult etc.
Examples:
public ActionResult A1()
{
 return View();
}
public PartialViewResult A2()
{
  return PartialView();
}
public JsonResult A3()
{
 return Json("MyJsonData");
}
public RedirectResult A4()
{
  return Redirect("url");
}
  • What should be the return type of an action method - ActionResult or specific derived type?
It's a good practice to return specific sub-types, but, if different paths of the action method returns different sub types, then it should be better to returen an ActionResult object. An example is shown below.
public ActionResult Index()
{
 if(Condition)
   return View();            // will returns ViewResult object
  else
 return Json("JsonData");  // will returns JsonResult object

}
  • What is StringLength attribute in ASP.NET MVC?
StringLength is used to enforce minimum and maximum length of characters that are allowed in a data field. This attribute is present in System.ComponentModel.DataAnnotations namespace.
[StringLength] attribute only verifies that a string is of certain length, but does not enforce that the property is REQUIRED. If you want to enforce that the property is required use [Required] attribute.
Example:
public class CustomerDetail
{
 [System.ComponentModel.DataAnnotations.StringLength(15, MinimumLength = 5)]
 [System.ComponentModel.DataAnnotations.Required]
 public string FullName { get; set; }

}
  • What is Range attribute in ASP.NET MVC?
RangeAttribute checks if the value of a data field is within a specified range of values.
public class CustomerDetail
{
 [System.ComponentModel.DataAnnotations.Range(1, 100)]
 public int Age { get; set; }
 [System.ComponentModel.DataAnnotations.Range(typeof(DateTime), "01/01/2020", "01/01/2040")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]

public DateTime BilledDate { get; set; }
}
In above piece of code, age text box only except values between 1 and 100. Same in Billed Date field, we can only set dates from 01/01/2020 to 01/01/2040.  Any value outside these ranges, will raise a validation error.
  • What does RegularExpression attribute do in ASP.NET MVC?
RegularExpression attribute is use for pattern matching validation.
Following string pattern enforce an email field which contains @ and a DOT symbol in it.
^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$
Example:
[System.ComponentModel.DataAnnotations.RegularExpression(@"^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$", ErrorMessage = "Please enter a valid email")]
public string EmailAddress { get; set; }
  • What does Compare attribute do in ASP.NET MVC?
Compare attribute is used to compare two properties of a model. Compare attribute is present in System.Web.Mvc namespace.
[System.Web.Mvc.Compare("ConfirmPassword")]
public string Password { get; set; }
At this point, this confirm attribute will ensure Password and ConfirmPassword properties have the same values. If they don't, then a validation error message is displayed.
  • How to enable Client Side Validation in ASP.NET MVC?
ASP.NET MVC provides both client and server side validation. There are two simple steps to enable client side validation in ASP.NET MVC.
Step 1: Enable ClientValidation and UnobtrusiveJavaScript in web.config file.
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
JavaScript is parsed "top-down", so all dependencies need to be referenced before the dependant reference. So, order in which the script files are referenced is very important. jquery.validate is dependant on jquery and jquery.validate.unobtrusive is dependant on jquery.validate, so they should be referenced in the following order. Otherwise, client side validation will not work. 
<script src="~/Scripts/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
With these two changes, validation should now ensue on the client without a round trip to the server. If the client disables javascript in the browser, then client side validation does not work, but server side validation will remain to work as.




(Practice Makes a Man Perfect)

No comments: