Wednesday, 19 June 2013

ASP.NET MVC, WCF, and LINQ Example

Introduction

This article is about a possible way to implement an N-Tier architecture for ASP.NET MVC (Model View Controller), using WCF (Windows Communication Foundation = replacement for .NET Remoting) and LINQ to SQL. This article will not go in depth explaining the ins and outs of MVC, WCF, and LINQ (there's already enough stuff which explains these technologies ...); instead, I'll be showing a possible way to implement these features in an N-Tier environment, by means of a simple bug-tracking demo application.

Requirements of the Bug-Tracking Demo Application

First, we should state the requirements of our demo application. These are quit straightforward, as mentioned beneath:
  • We want the application to produce a list of currently added bug-tracking tickets.
  • We want the possibility that a user can add a ticket to the system, which evolves adding a ticket date, selecting a user to whom we grant the ticket, adding a ticket date, and letting the user add some comments.
  • Before adding a new ticket to the system, we want to be sure that the user has supplied a valid date, selected a ticket type and user, and added some comments for the ticket.

Architectural Overview

architecture.jpg
The .NET Solution consists of three main projects:
  • BtDataLayer: Contains the model classes and the data access routines.
  • BtWcfService: Contains the services which the presentation layer may call.
  • BugTracking: Contains the presentation layer (ASP.NET MVC app).
Another project not mentioned on the diagram above is CommonLib, which contains the commonly used routines (like a business base class which each model class derives from, method for cloning objects, and a business rule validator engine).

Using the Code

The Data Access Layer (BtDataLayer)

  • The model classes (BugTracker.dbml):
  • bugtrackrelations.jpg
    These are the LINQ-TO-SQL classes retrieved from the SQL-Server Bugtracker database (database template included in the Zip file). As this model should be remotable, the serialization mode on the datacontext should be set to Unidirectional.
  • The Data Access Code (btDataManger.cs):
  • We want to be able to load a user-list so we can select a user for whom the ticket applies to:
     
    public static List<user> GetUserList()
    {
       // Create the DataContext to retrieve the Users from.
       BugTrackerDataContext db = new BugTrackerDataContext();
    
       // Return a list of Users.
       return db.Users.ToList<user>();
    }
    We want to be able to load a tickettype list, so we can select the type of ticket (BUG, INFO, etc ...) for the ticket:

    public static List<tickettype> GetTicketTypeList()
    {
       // Create the DataContext to retrieve the Ticket Types from.
       BugTrackerDataContext db = new BugTrackerDataContext();
    
       // Return a list of TicketTypes.
       return db.TicketTypes.ToList<tickettype>();
    }
    We want to be able to retrieve all the current tickets from our ticket table:

    public static IEnumerable<ticket> GetTickets()
    {
       // Create the DataContainer to retrieve the tickets.
       BugTrackerDataContext db = new BugTrackerDataContext();
                
       // Return a List of Tickets
       return db.Tickets;
    }
    Finally, we want to have the possibility to persist a newly added ticket (one at a time for the demo application, but we make the method all-purpose, so it can accept many added or modified objects):

    public static bool PersistTickets(ref TicketList p_tickets)
    {
        // Only persist if any tickets to add or modify.
        if (p_tickets == null || p_tickets.Count == 0)
            return false;
    
        // Create the persistence datacontext
        BugTrackerDataContext db = new BugTrackerDataContext();
    
        // Persist any new or modified tickets.
        foreach (Ticket t in p_tickets)
        {
            if (t.TicketId == 0)
            {
                db.Tickets.InsertOnSubmit(t);
    
            }
            else
            {
                db.Tickets.Attach(t, t.IsDirty);
            }
        }
    
        try
        {
            db.SubmitChanges(ConflictMode.ContinueOnConflict);
    
            // Reset the isDirty flag.
            foreach (Ticket t in p_tickets)
            {
                t.IsDirty = false;
            }
    
        }
        catch (ChangeConflictException ex)
        {
            throw ex;
        }
    
        return true;
    }

The Service Layer

The purpose of our WCF enabled service layer is to make the model and data-access routines (to foresee the model of data ...) available to the presentation layer.
Our service layer consists mainly of two routines:
  • The service contract (which contains the routines which can be called by our Web App).
  •  
    [ServiceContract]
    public interface IBtService
    {
        [OperationContract()]
        IEnumerable<user> GetUserList();
    
        [OperationContract()]
        IEnumerable<tickettype> GetTicketTypeList();
    
        [OperationContract()]
        bool PersistTickets(ref TicketList p_tickets);
    
        [OperationContract()]
        IEnumerable<ticket> GetTickets();
    }
  • The Service Implementation, which implements our contract and calls the datalayer.
  •  
    public IEnumerable<user> GetUserList()
    {
        return BtDataManager.GetUserList();
    }
    
    public IEnumerable<tickettype> GetTicketTypeList()
    {
        return BtDataManager.GetTicketTypeList();
    }
    
    public bool PersistTickets(ref TicketList p_tickets)
    {
        return BtDataManager.PersistTickets(ref p_tickets);
    }
    
    public IEnumerable<ticket> GetTickets()
    {
        return BtDataManager.GetTickets();
    }

The Presentation Layer

The presentation layer contains our ASP MVC application. As already mentioned above, I will not go in depth on MVC, as there is already a lot of info available on the net. But it is important to know that MVC contains three main items, namely the Model (which represents our class, a validation logic, and is remotely available through the Service Layer), the View (our webpage), and the Controller (which basically "hooks" the Model to the View).

The Views and the Controllers

Our demo application hosts the following MVC enabled web pages:
Ticket.aspx
ticket.jpg
With this page, the user can add a bug-ticket to the system. The HomeController is responsible for rendering the page. While interacting with the page, there are two actions involved, one for creating a new ticket (the "GET") version, and one for persisting a new ticket (when the user hits the Submit button: the POST version).

 


[AcceptVerbs("GET")]
public ActionResult Ticket()
{
    this.LoadSelectionLists();

    // Get the userlist
    var userList = new SelectList(_userList, "UserId", "Username");
    ViewData["UserId"] = userList;

    // Get the tickettypelist
    var ticketTypeList = new SelectList 
    (_ticketTypeList, "TicketTypeId", "TicketTypeDescription");
    ViewData["TicketTypeId"] = ticketTypeList;

    return View();
}

When the user selects "Create Ticket" in the index page, we must create a new page where the user may enter the ticket details. As the user should have the possibility to select a user and ticket type for the ticket, these data are loaded from the service and added to the viewstate of the form:

 


private void LoadSelectionLists()
{
    // Get a proxy to the data service provider
    BtServiceRef.BtServiceClient proxy = new   
    BugTracking.BtServiceRef.BtServiceClient();

    // Get the userlist
    _userList = proxy.GetUserList();
    
    // Get the tickettypelist
    _ticketTypeList = proxy.GetTicketTypeList();
   
}

On the other hand, the post version is executed when the user hits the "Submit" button. We will create a ticket object, map the properties to the field properties of the form, validate the objects data (see the source code of the model for detailed validation information as validation data is stored in the model classes), and persist the newly added ticket through the service to the database.

 


[AcceptVerbs("POST")]
public ActionResult Ticket(FormCollection p_form)
{
    // Create placeholder for the ticket to add.
    var TicketToCreate = new Ticket();

    
    try
    {
        // Map the controls of the View to the PlaceHolder.
        this.UpdateModel(TicketToCreate, new[]  
        { "UserId", "TicketTypeId", "Comment", "GrantedToDate" });
        
        // Force Validation
        TicketToCreate.Validate();

        // First check if any validation Errors Exist on the newly 
           added ticket
        if (TicketToCreate.HasErrors)
        {
            
            // View Validation Errors

            foreach(DictionaryEntry entry in  
            TicketToCreate.ValidationErrors)
            {

                ViewData.ModelState.AddModelError(entry.Key.ToString
                (), entry.Value.ToString());
            }
            
            throw new InvalidOperationException();
        }
        else
        {
            // Create the WCF Remote service and let the service 
               persist the new ticket.
            BtServiceRef.BtServiceClient proxy = new 
            BugTracking.BtServiceRef.BtServiceClient();
            Ticket[] newTicketList = new Ticket[] { TicketToCreate };
            proxy.PersistTickets(ref newTicketList);
        }
       
    }
    catch
    {
        this.LoadSelectionLists();

        var userList = new SelectList(_userList, "UserId", "Username");
        ViewData["UserId"] = userList;

        var ticketTypeList = new SelectList  
        (_ticketTypeList, "TicketTypeId", "TicketTypeDescription");
        ViewData["TicketTypeId"] = ticketTypeList;


        // Show possible validation errors.
        return View(TicketToCreate);
    }
    
    // Return to main page.
    return RedirectToAction("Index");
}

There are two comboboxes on the ticket.aspx form: one for user selection and one for ticket type selection. As shown in the code above, we load the user and ticket type records from the service and add them as ViewData of the ticket page. Next, we have to bind the ViewData as mentioned below (you can also notice how we execute the bindings for validation purpose):
dropdown.jpg
Index.aspx
When loading the application in the browser, the index page is the first page shown. We get a list of current tickets in the database and the possibility to add a new ticket to the system:
indexpage.jpg
Again, the HomeController is responsible for rendering the page, the action involved is:

 


public ActionResult Index()
{
    ViewData["Title"] = "Home Page";
    ViewData["Message"] = "Welcome to ASP.NET MVC Bugtracker !";

    // Create a proxy to the WCF service.
    BtServiceRef.BtServiceClient proxy = 
       new BugTracking.BtServiceRef.BtServiceClient();

    // Get all tickets from the DataLayer.
    return View(proxy.GetTickets());
}

As we will show the current tickets in this page, we first create a reference to our service. This service calls the GetTickets() method of our data layer data-access class and adds it as input parameter of the view. Next, to be sure that our Index Page is aware of the loaded ticket-list, the BtDataLayer.Ticket type should be added as an attribute to the derived ViewPage:

indexpage_classdef.jpg

Finally, in the HTML code of our index.aspx page, we can loop through our loaded ticket list and place each ticket in a data row:

tickets_in_table.jpg

You may have noticed that I display the UserId and TickeTypeId instead of the user name and ticket type description. If you want to view, for example, the username instead of the ID, you should use: t.User.UserName, but this will return an error, as the user is not loaded with the tickets. You can change this by altering the data access method and adding data load options for the user and ticket type. In this case, the related user and ticket type objects will be loaded too.

Click here for  Reference

WebGrid in MVC 3

The latest ASP.NET MVC version, hand in hand with WebPages technology, brings us a new set of productivity helpers that are quite interesting in the namespaces System.Web.Helpers. Among them we find WebGrid, which finally offers a powerful and flexible default solution to help us implement this useful feature in our applications.
Let’s see, step by step and in a completely practical manner, how to use WebGrid.

1. First: the Model


The first thing we need before we begin to go in depth in the WebGrid helper is a Model, the app’s data entities as well as the tools that enables us to make persistant and recover the information from the storage system we are using.
In this case, we are going to use as a repository a SQL Express database with a single table, in which we have stored some people’s data; this collection is the one we want to display in a datagrid. Therefore, we have to fill it in with data to test it later.
In order to access the database we are going to use Entity Framework. To do so we are going to need an Entity Data Model (a conceptual entity model), which we can add to the project’s Models folder by selection the ”Add new item” option from the context menu. In the wizard that comes up, we only have to indicate it that we are going to generate the model from an exisiting database, and finally we select the table “People”. One we’ve finished this operation, we already have the basic data infrastructure for our application.
The next step is to create a services class, which provides the business logic and data access to our system. Obviously this does not always have to be this way, since it depends on our needs and the software’s architecture, and in our example both are going to be quite simple.
The starting code for our services class is as follows:
01public class ModelServices: IDisposable {
02   private readonly Entities entities = new Entities();
03   public IEnumerable GetPeople()
04   {
05      return entities.People.ToList();
06   }
07   public void Dispose()
08   {
09       entities.Dispose();
10   }
11}
As you can see in the previous code, we have a single method called GetPeople(), which returns the complete set of people stored in the database.
And for now this is all the Model we need for the time being.

2. The controller

Our controller class, which we’ll call PeopleController, in this first approach is going to be really simple. A single action, Index(), which returns a view which we will supply the data collection obtained from the Model to:
01public class PeopleController : Controller
02{
03    public ActionResult Index()
04    {
05        var data = new ModelServices().GetPeople();
06        return View(data);
07    }
08}
An this is it: an action two lines. OK, it could have been performed in a single line, but this way the code is more readible ;-)

3. The View, take one: WebGrid comes into scene

Now it’s when we really begin to notice the advantages of using WebGrid versus other options available until MVC and that we have mentioned at the top of this post.
Look at the following code, a  Razor view that receives an number of Person objects form the controller and generates a complete grid:
01@model IEnumerable<Person>
02@{
03    ViewBag.Title = "People";
04    WebGrid grid = new WebGrid(Model);
05}
06<h2>People</h2>
07@grid.GetHtml()
Impressing, isn’t it? Even though it seems incredible, the previous code is all we need to build a completely functional grid, with paging and column order: two lines! In the first line we instance the WebGrid providing it the data collection on which it has to iterate. In the second one we generate the HTML markup we’ll send to the client. The result of executing this code is displayed below:

Although it’s far from being perfect, the result is spectacular. The helper’s default behaviour displays a column for each property that it finds in the class on which it iterates, putting them in alphabetical order. In addition, it uses the name of the properties as column headings, and displays them as links to force the sort order by each one of them, and it even enters in the footer a complete data page navigation system. And the best thing is that all thid works directly, without having to add more code lines :-)
Nevertheless, as always, these automatisms have a cost. On one hand, we don’t control the columns to be displayed. Neither do we control the format in which its values are shown (see, for instance, the date of birth) nor their headings…
Normally we have to put in an extra effort (not much though) in order to leave everything perfectly. Moreover, there is a serious performance problem when the number of  grid elements is large:  both the sort order and the paging are performed on memory with the total number of items. Exagerating a bit, let’s suppose we have one million rows in the database, one million objects will materialize on memory, will be ordered according to the current criteria and, finally, only the ten objects that a data page contains are displayed to the client. Further on, we’ll see that there are some formulas to manage efficiently these scenarios.
[Learn MVC 4 step by step with the post author: 'Expert Web Development with ASP.NET MVC 4' created and tutored by Jose M. Aguilar]

4. The View, take two:  the columns I want, please

There are different formulas to specify the columns to be displayed in a WebGrid. The first of them is by exclusion on the total set of properties. Among many other aspects, we can specify in the GetHtml() method an array of name properties which mustn’t be shown as columns. For instance, taking the previous example, if we are interested in showing the PersonId property, we could have substituted the last line of the view for:
01@grid.GetHtml(exclusions: new[] {"PersonId"})
However, the previous approach is not very useful, since want we generally want is to indicate the order in which the columns are displayed, specify their headers, determine whether or not the columns can be used as order criteria, etc. All this information is defined in WebGridColumn objects. Despite there are other ways of doing it, we habitually find in the columns parameter of the GetHtml() call an array with the detail of the grid columns, like in the following example:
01@grid.GetHtml(columns: new [] {
02    grid.Column("Name"),
03    grid.Column("Surname"),
04    grid.Column("EMail"),
05    grid.Column("BirthDate"),
06    grid.Column("Children")
07})
As we can see, we are passing in the columns parameter an array in which each element is being generated by a call to the WebGrid Column() method, in which first parameter we indicate the name of the property  that the column corresponds to. The result of executing the code using this last code would be:

Somethings have improved, but we still have to tweak the way it is displayed.

5. The View, take three: the columns how I want, please

We still have to shore up several details for the grid to reach, at least visually, reasonable standards. To customize each column we can use the parameters form the Column() column generator method which we have seen above:
  • header, which allows to indicate the text shown in the header,
  • canSort, which indicates if the column can be used as sort order criteria,
  • format, which enables us to indicate a custom format for column content,
  • style, which indicates CSS class that will be applied to all the column cells.
Of all of the above, only the format property deserves a special mention. In it we can indicate, either through a Razor markup block or through the lambda function, how the content of the property vinculated to the column has to be formated. In the first case, we should start the markup block with the Razor escape character (@) and follow it with the code we want to send to the client. From inside we can make  reference to the object which is being evaluated by using @item, like in the following example, where how to format the EMail column so it is displayed as a mailto hyperlink:
01grid.Column("EMail",
02             format: @<a href="mailto:@item.Email">@item.Email</a>
03)
We can also use the lambda function, which receives as parameter the current item and returns a string (or a IHtmlString if it doesn’t have to be encoded). For instance, next we’ll see how to use this possibility to give format to the BirthDate column:
01grid.Column("BirthDate",
02            format: p=>p.BirthDate.ToShortDateString()
03)
Therefore, bearing in mind all the above, we can tweak the grid a bit by using the following code. As a reminder, I’ll show the again the complete code of the view, so you can see how it results entirely:
01@model IEnumerable<Person>
02@{
03    ViewBag.Title = "People";
04    WebGrid grid = new WebGrid(Model);
05}
06<h2>People</h2>
07@grid.GetHtml(columns: new [] {
08    grid.Column("Name", canSort: false),
09    grid.Column("Surname"),
10    grid.Column("EMail",
11                 format: @<a href="mailto:@item.Email">@item.Email</a>
12    ),
13    grid.Column("BirthDate",
14                header: "Birth date",
15                format: p=>p.BirthDate.ToShortDateString()
16    ),
17    grid.Column("Children",
18                header: "Children",
19                style: "to-the-right"
20    )
21})
In runtime we can see now how it’s almost finished:

6. The View, take four: And can’t I add custom columns?

Of course you can! In fact, you can do it by just adding columns like before, except that we don’t have to link them to any Model class property. This, combined with the flexibility of the custom format (format parameter), offers us everything we need to create columns the way we want to. The code below shows how to add an additional column with links to the actions that would enable it, for instance, to edit or delete a Person:
01@grid.GetHtml(columns: new [] {
02    ... // Rest of grid columns, seen previously
03    grid.Column(
04       "",
05        header: "Actions",
06        format: @<text>
07                @Html.ActionLink("Edit",   "Edit",   new { id=item.PersonId} )
08                |
09                @Html.ActionLink("Delete", "Delete", new { id=item.PersonId} )
10               </text>
11    )
12})
Notice how, to increase the code’s legibility, we are using the special Razor tag that allows us to create mark up blocks for several lines. The result is as follows:

7. The View, take five: I’d rather have it all as I want to

The WebGrid helper offers a bunch of extra customizing options that we can set when both calling it’s different methods or doing so directly. For instance GetHtml() enables us to indicate the following parameters, besides those that we have already studied:
  • headerStyle, footerStyle, rowStyle, alternatingRowStyle, and selectedRowStyle enable to indicate the CSS classes to apply to the header, footer, alternative data rows and selected row, respectively.
  • caption, to specify a title for a table, which will be included in a tag.
  • fillEmptyRows, set to true it makes each page have always the same number of rows, creating blank rows if needed.
  • emptyRowCellValue indicates the value to be shown in the empty row cells.
  • mode, enables specifying the type of paginator to be created, choosing it through a combination of elements of the WebGridPagerModes numbering:
    • WebGridPagerModes.Numeric: the pagainator shows all the direct links to pages near the current one.
    • WebGridPagerModes.FirsLast: links to go to the first or last data page are displayed.
    • WebGridPagerModes.NextPrevious: links to go to next or previous page are displayed.
    • WebGridPagerModes.All: all of the above at the same time.
  • numericLinksCount: indicates the number of pages that will appear whenever the mode contains the  WebGridPagerModes.Numeric value.
  • firstText, previousText, nextText, lastText, enables replacing the texts that appear by default in the go to first, previousm next and last page links respectively. Initially “<”, and “>>” is common.
For example, take a look at the following code and its runtime result once we have created a pair of rules in the web page style sheet:
01<h2>People</h2>
02<pre>@grid.GetHtml(
03    fillEmptyRows: true,
04    alternatingRowStyle: "alternative-row",
05    headerStyle: "grid-header",
06    footerStyle: "foot-grid",
07    mode: WebGridPagerModes.All,
08    firstText: "<< First",
09    previousText: "< Previous", nextText: "Next >",
10    lastText: "Last >>",
11    columns: new [] {
12     ... // column definition seen previously
13 
14})
Also, the WebGrid builder itself enables editing several functional aspects of the grid using the following parameters:
  • defaultSort, it indicates the column that will act as default order while no other one is specified.
  • rowsPerPage (by default, 10), defines the number of rows that appear on each page.
  • canPage, canSort, indicate respectively if the grid allows paging and sort order. By default it is set to true in both cases.
  • fieldNamePrefix, it enables indicating the prefix that is going to be used in the query string parameters used by the grid. This, for instance, will allow us to show several grids simultaneously on the same page, without interfering.
  • selectionFieldName, sortFieldName, sortDirectionFieldName enable indicating the name of the parameters used to keep the state of the selecetd row, the ordering field, and the direction of the ordering.
WebGrid even enables working in Ajax mode. In other words, it is able to display the different pages without loading the entire page. In this case, we can use the ajaxUpdateContainerId and ajaxUpdateCallback parameters, that allow us to indicate the element of the page where the data will be displayed and a callback function that will be called after updating the element.

Friday, 14 June 2013

Extension Method in Asp.Net with C#

What is an Extension Method?

Extension methods enable us to add new methods to existing types.

Then what makes it so different?

  • To do it we are not required to modify the existing type.
  • No Inheritance is involved.
  • They are static by nature (but called as if they are instance methods on the extended type).
How to create?

Step 1

Create a static class called PageExtensions as:

public static class ClsPageExtenions
{
}

Step 2

Create a static method IncludeJavaScript and IncludeStylesheet in that class as:
 
public static void IncludeJavascript(this Page objPage, string strJsPath)
{
    HtmlGenericControl objJs = new HtmlGenericControl();
    objJs.TagName = "script";
    objJs.Attributes.Add("type", "text/javascript");
    objJs.Attributes.Add("language", "javascript");
    objJs.Attributes.Add("src", objPage.ResolveClientUrl("~/Javascript/" +
    strJsPath));
    objPage.Header.Controls.Add(objJs);
}
public static void IncludeStylesheet(this Page objPage, string strCssPath)
{
    HtmlGenericControl objCss = new HtmlGenericControl();
    objCss.TagName = "link";
    objCss.Attributes.Add("type", "text/css");
    objCss.Attributes.Add("rel", "stylesheet");
    objCss.Attributes.Add("href", objPage.ResolveClientUrl("~/CSS/" + strCssPath));
    objPage.Header.Controls.Add(objCss);
}

Note: The first parameter must be preceded this modifier, telling the compiler that this is an extension method for the Page Class.

Step 3

Create the client code as:
 
protected void Page_Load(object sender, EventArgs e)
{
          this.IncludeJavascript("MyJs.js");
          this.IncludeStylesheet("MyCss.css");
}

That's it, for the client code there will not be any difference between normal methods and Extension methods.

Thursday, 16 May 2013

ASP.Net MVC Interview Questions and Answers

About ASP.Net MVC



The ASP.Net MVC is the framework provided by Microsoft that lets you develop the applications that follows the principles of Model-View-Controller (MVC) design pattern. The .Net programmers new to MVC thinks that it is similar to WebForms Model (Normal ASP.Net), but it is far different from the WebForms programming. 
This article will tell you how to quick learn the basics of MVC along with some frequently asked interview questions and answers on ASP.Net MVC

1. What is ASP.Net MVC

The ASP.Net MVC is the framework provided by Microsoft to achieve     separation of concerns that leads to easy maintainability of the     application.
Model is supposed to handle data related activity
View deals with user interface related work
Controller is meant for managing the application flow by communicating between Model and View.

2. Why to use ASP.Net MVC

The strength of MVC (i.e. ASP.Net MVC) listed below will answer this question
  • MVC reduces the dependency between the components; this makes your code more testable.
  • MVC does not recommend use of server controls, hence the processing time required to generate HTML response is drastically reduced.
  • The integration of java script libraries like jQuery, Microsoft MVC becomes easy as compared to Webforms approach.

3. What do you mean by Razor

The Razor is the new View engine introduced in MVC 3.0.
The View engine is responsible for processing the view files [e.g. .aspx, .cshtml] in order to generate HTML response.
The previous versions of MVC were dependent on ASPX view engine. 

4. Can we use ASPX view engine in latest versions of MVC

Yes. The Recommended way is to prefer Razor View

5. What are the benefits of Razor View?

  •      The syntax for server side code is simplified
  •      The length of code is drastically reduced
  •      Razor syntax is easy to learn and reduces the complexity

6. What is the extension of Razor View file?

.cshtml (for c#) and .vbhtml (for vb)

7. How to create a Controller in MVC



Create a simple class and extend it from Controller class. The bare minimum requirement for a class to become a controller is to inherit it from ControllerBase is the class that is required to inherit to create the controller but Controller class inherits from ControllerBase.

8. How to create an Action method in MVC

Add a simple method inside a controller class with ActionResult return type.

9. How to access a view on the server   

The browser generates the request in which the information like Controller name, Action Name and Parameters are provided, when server receives this URL it resolves the Name of Controller and Action, after that it calls the specified action with provided parameters. Action normally does some processing and returns the ViewResult by specifying the view name (blank name searches according to naming conventions).

 

10. What is the default Form method (i.e. GET, POST) for an action method

GET. To change this you can add an action level attribute e.g [HttpPost]


11. What is a Filter in MVC?


When user (browser) sends a request to server an action method of a controller gets invoked; sometimes you may require executing a custom code before or after action method gets invoked, this custom code is called as Filter.


12. What are the different types of Filters in MVC?


a. Authorization filter

b. Action filter

c. Result filter

d. Exception filter

[Do not forget the order mentioned above as filters gets executed as per above mentioned sequence]



13. Explain the use of Filter with an example?


Suppose you are working on a MVC application where URL is sent in an encrypted format instead of a plain text, once encrypted URL is received by server it will ignore action parameters because of URL encryption.

To solve this issue you can create global action filter by overriding OnActionExecuting method of controller class, in this you can extract the action parameters from the encrypted URL and these parameters can be set on filterContext to send plain text parameters to the actions.    



14. What is a HTML helper?


A HTML helper is a method that returns string; return string usually is the HTML tag. The standard HTML helpers (e.g. Html.BeginForm(),Html.TextBox()) available in MVC are lightweight as it does not rely on event model or view state as that of in ASP.Net server controls.