Thursday, January 29, 2015

View Method, ViewData and TempData in MVC5


Views provide the user interface as response to an action. In general, when the user hits a URL, it gets mapped to a controller action and the controller action then returns a view which contains the HTML supposed to be rendered by the browser.

When we look at the default Home Controller's Index() method, we see that it simply returns the result of the View() method.

public class HomeController : Controller
        public ActionResult Index()
            return View();

Let's take a look at what happens under the hood.

Controller.View() Method

The View() method creates an object of type ViewResult and returns it. This object is responsible for rendering the View. Inside the View() method in controller class, we just simply set the properties like: ViewName, masterName and model. The View method in controller class has multiple overloads for different combinations of the aforementioned three properties. For any of the overloads, if some property is not set, it is simply set to null
i)   View()
ii)  View(object model)
iii) View(string viewName)
iv) View(string viewName, object model)
v)  View(string viewName, string masterName)
vi) View(string viewName, string masterName, object model)

viewName is used to pass the name of the view. model is used to pass the viewmodel i.e. data to be rendered in the view. masterName is used to specify the name of the master page to be rendered.
Other than these, there are 2 more overloads of the View method which take the IView object and model:
vii) View(IView view)
viii) View(IView view, object model)

view parameter is used to specify the view to be rendered.
So once these properties are set inside the ViewResult object and returned, the ASP.NET MVC framework calls the ExecuteResult() method of the ViewResult object in order to render it. I have already talked about ExecuteResult() method in a previous blog post.

Default View Path

About ViewPath, I want to mention one thing i.e. If no view name is passed, by default the MVC framework searches for a view at Views/[Controller]/[Action].cshtml. So for the HomeController's Index Action, we get /Views/Home/Index.cshtml view.

ViewBag, ViewData & ViewDataDictionary

ViewData is of type ViewDataDictionary which is a specialized dictionary. It is used to pass data between controller and view. Inside the controller action method, we can pass value to the view like this:

ViewData["color"] = "red";

And In the View, we can use that value like this:


Similarly, we can pass the data in reverse direction as well i.e. from view to controller action.

ViewBag is a dynamic wrapper around ViewData. It's just syntactical sugar which allows us to access the same data like this:


They both point to the same data in terms of memory. So we can even set value for ViewData["color"] and access it using ViewBag.color, if we want.


Our discussion won't be complete if we talk about ViewData and don't talk about TempData. This is similar to ViewData in the sense that its also used to send data between controller and view but the key difference is, it is used to send data between current and next HTTP Requests. When we redirect as part of an action method result, a new HTTP request is generated from the browser to the redirected route. In such a case, if we have anything set in the ViewData, it won't be available to us because ViewData is accessible only per request. In such a scenario, we can use TempData. Syntactically, its similar to ViewData.

public ActionResult Index()
            TempData["mycolor"] = "black";
            return Redirect("Home/About");


Overall, Controller's View method's various overloads give us control which view to render and the viewmodel to be passed in. MVC provides us with some default convention to follow for organizing our views in the directory but it also allows us to easily override those if needed. Also, in this post we discussed the underlying structure of ViewData and when to use ViewData and TempData.

For future updates to my weekly blog, please subscribe to the blog and follow me on Twitter.

Thursday, January 22, 2015

Elements Tab in Chrome Developer Tools

When I see people struggling with Internet Explorer Debug tools, or making a small UI change in the application and re-running the whole solution through visual studio, I feel like it's high time I write a post on Chrome Developer tools. I was discussing the Chrome's power with a friend of mine and he suggested me to write a post on it. Chrome Developer tools are far ahead in features as compared to what's available with any other tool for convenient application development and debugging.

So let's hit the F12 key (or right click Inspect Element) and start rolling. In general, there are 8 tabs, I am going to focus on the Elements tab in this post.

Elements Tab

Editable DOM

The Elements tab shows nicely formatted HTML. We can easily navigate through the DOM structure and understand how the document is laid out. We can see information for any HTML element like the class, id, divs, head etc. You can edit anything like classes or text and see how the page looks. This is great if you are debugging or see how the page will look once its rendered. We don't have to go to Visual studio, change some small text and run the solution again to see how it looks. You have the editor right here in the browser.

You can even see the DOM element structure at the bottom. When we select an element, it's parents are shown to the left. We can select any parent from the bottom line and navigate through the HTML easily. As seen in the Fig 1, td element is highlighted

DOM Structure

Search/ Ctrl+F

We can search for any element in the page. We can even use XPath and CSS selectors. I use CSS selectors pretty often. For example, I want to see how many elements use this class I will use ".myClass" in my search box. I think this is really cool.

CSS Styles

On the right hand side, we see the Styles window. We can play with the css right here and see the results immediately. Once we have a satisfactory look and feel, we can just copy the css and paste it into our solution. Doesn't it make our life easy.
The CSS window allows us to check/uncheck any property, search for the properties, add new properties and edit existing ones. One thing that I want to explicitly mention which is very helpful is when I edit the color property, I can use color picker and choose which color I want to use.

Color Picker

Toggle Element State

If we want to see how a specific element looks in different states like focused or active, we can test it by just using these checkboxes as shown in Fig. This is particularly helpful when we have multiple nested elements and we need to see how these elements state affect one another. Hovering a mouse on them activates hover on both the nested elements. But with these we can debug each individual item separately.

Element State

New Style Rule

Plus Sign adds css style to the specific class you are currently accessing. We can add css to the specific class and we can examine the results applied to the whole class simultaneously.

New Style

Computed Tab

The computed tab shows the final computed style rules that are rendered on screen. If we click on the arrow to the left of the style, it shows the source file and line number.  

Computed Tab

DOM Breakpoints

This is yet another useful feature while debugging. If we want to see who is adding, removing or modifying elements to a specific DOM element, we can  put a breakpoint on the DOM element. As shown, we have three options:
i) Subtree Modification 
ii) Attributes Modification
iii) Node Removal

Adding DOM Breakpoint

This will stop the application at any point where the specific action is invoked. This helps us in debugging issues related to any kind of dynamic DOM manipulation. 


This window lets us edit the properties of any HTML element on the fly. As shown in the figure, I can edit the innerText property and see the results on the fly.

Chrome Properties

Event Listeners

This is one feature that I don't like much. This shows the events attached to a specific element. However, clicking on it doesn't always navigate us to the actual callback function. For example, if I used jquery to bind click event to a specific element, navigating to the click event shows me click event in jquery file which is of not much use to me. I think this will improve in future but for now this is helpful sometimes, not always.


This is the power of just the Elements tab of Chrome. I will explain other tabs in future posts. I hope it was useful and you got to learn something new out of this post.

For future updates to my weekly blog, please subscribe to the blog and follow me on Twitter.

Thursday, January 15, 2015

ASP.NET MVC5 Action Methods and Action Results

In this post, I am going to talk about what Action Methods are and different Action Result Types available to us in ASP.NET MVC5.

Action Methods

An action method gets executed in response to a user request. It takes care of processing the user input and building the response to be sent to the user. If we look at the HomeController that comes with a default MVC project, we see some action methods already created.

public class HomeController : Controller
        public ActionResult Index()
            return View();

When we request /Home/Index, this action method is called which returns the view(Home/Index.cshtml).

Writing our own action methods is crucial to our MVC application development as we will be adding/editing our own functionality by adding/ editing these action methods. The return type of this action method is ActionResult.
In general, an Action Method does the stuff we write inside the method and then returns an instance of a type derived from ActionResult abstract base class.
Let's try to understand what ActionResult is and what are the other return types possible and their usages.


This is a generic return type for the controller action methods. It's basically an abstract class with one method: ExecuteResult()

 // Summary:

    //     Represents the result of an action method.

    public abstract class ActionResult

        // Summary:

        //Enables processing of the result of an action 
        //method by a custom type that

        //inherits from the System.Web.Mvc.ActionResult




        //The context in which the result is executed. 
        //The context information includes

        //the controller, HTTP content, request context,
        //and route data.

        public abstract void ExecuteResult(ControllerContext 


Action methods take care of the application logic whereas ActionResults are supposed to handle framework level work such as writing to HttpResponse directly. The ExecuteResult method is called by the MVC framework to run the action result.We can override the ExecuteResult() method and write our own custom Action Result Types. Here, let's take a look at the pre-built Types which take care of most of our application needs.

Action Result Types

This Writes the specified content directly to the response as text. We can use this for any content type. We can specify the content encoding and content type. Using this, we can give the system whatever response we want.

Returns a null or empty response. We can use it for blank page.

This is derived from the abstract class FileResult. This is used to read the file contents and then write byte array to response's output stream.

This is also derived from FileResult abstract class. This is useful when we want to read the file from a specific path. Using this we can write the file directly to the response from the specified path.

This is just an abstract base class which is used by other types for returning files to the user. It contains an abstract method WriteFile() which is overridden by the other types deriving from it. FileContentResult, FilePathResult and FileStreamResult derive from this.

This is also derived from FileResult abstract class. This is useful when we want to read the file and write a stream to the response.

This is used to send the HTTP 404 Not Found response to the client. This is derived from HttpStatusCodeResult.

This is used to return a specific HTTP Code and description to the client. 

This is used to send the HTTP 401 Not Authorized response to the client. This is also derived from HttpStatusCodeResult.

This is used to send Javascript code to the client to be execute immediately. Here, the content type is automatically set to “application/x-javascript”.

This uses javascript serializer to return the data serialized in JSON format. Here, the content type is automatically set to “application/json”. This is typically used to return response for AJAX requests.

This is used to render partial view to the response. This is also typically used to return response for AJAX requests. Internally, it calls its FindPartialView method to find the partial view to be rendered.

This is used to perform HTTP redirect to a specified URL. It sends response with status code 302 Object Moved. This will cause the client to issue a new request immediately to the specified URL.

This is also used to perform HTTP redirect similarly but instead of a specific URL, we just mention the route and then routing API is used to get the URL.

This is the last but most widely used Result Type. This is derived from ViewResultBase class. The FindView method is used to locate the view and the Render method is used to render the output to the response.

These different result types give us a lot of power to deal with different scenarios effectively. They are pretty simple to learn and easy to use.

Reference: "Professional ASP.NET MVC 5"

Thursday, January 8, 2015

Controllers in MVC

In this third blog post, I am going to talk about the heart of an MVC application: The Controllers.


In old web applications, there used to be a direct relationship between the URL and web server's hard drive. In an MVC application, similar relationship exists between the URL and controller's action methods. That will become more clear when I explain routing in a future post. Until then, just understand that routing allows us to map a URL to a controller action.
Controllers are the classes which respond to user input. It contains the actions that are executed on a user request and build a response that is returned to the user. In other words, they control the flow of execution, i.e. they work with the data coming in and provide the data going out to the relevant view.

By now, I will expect that you have installed an MVC project in Visual Studio 2013. By default, the project has 2 controllers: HomeController and AccountController. Technically, controller is a simple class derived from System.Web.MVC Controller class. Let's talk about this in detail.

Controller Class

If we take a closer look at the Controller class, we will see that it's an abstract class derived from ControllerBase class and implementing a bunch of interfaces where IController is one of the interface.

public abstract class Controller : ControllerBase, 
       IActionFilter, IAuthorizationFilter, IDisposable, 
       IExceptionFilter, IResultFilter, IAsyncController, 
       IController, IAsyncManagerContainer

Since its an abstract class, we cannot instantiate it directly. In order to understand the relationship between IController, ControllerBase and Controller classes, lets take a closer look at these.


 IController interface has an Execute method which gets executed when a request is made for the controller. This takes RequestContext as a parameter. When a request cones in, the routing system identifies the appropriate controller and executes the Execute method

// Summary:
    //     Defines the methods that are required for a 
    //     controller.
    public interface IController
        // Summary:
        //     Executes the specified request context.
        //     The request context.
        void Execute(RequestContext requestContext);


ControllerBase is another abstract base class that layers some more API surface on top of the IController interface. It implements Execute method of IController where it creates ControllerContext, which in turn, encapsulates information about HTTP request that matches specified RouteBase and ControllerBase instances.
It also provides TempData, ViewData, ViewBag, etc. We can look at their data types here. ViewData and ViewBag are used to send data from controller to view. ViewData is a dictionary in nature used to store key value data. ViewBag is simply a wrapper around ViewData. TempData is used to send data across subsequent requests.
namespace System.Web.Mvc


    public abstract class ControllerBase : IController


        protected ControllerBase();

        public ControllerContext ControllerContext { get; 
                                                     set; }

        public TempDataDictionary TempData { get; set; }

        public IValueProvider ValueProvider { get; set; }

        public dynamic ViewBag { get; }

        public ViewDataDictionary ViewData { get; set; }

        protected virtual void Execute(RequestContext 

        protected virtual void Initialize(RequestContext 



Controller Class

So let's come back to the controller class. The Controller class is also an abstract class which is derived from controller base and implements IController interface. It contains all the useful properties and methods for a controller to work out properly.

We can define our own Controller class from ControllerBase

public class TestController : ControllerBase
    protected override void ExecuteCore()
        throw new System.NotImplementedException();

    public ActionResult Index()
        return null;

So when we try hit the URL Test/Index, ExecuteCore() is executed first and then Index() is called. Technically, we can implement these but we don't need to. Microsoft has already done all this for us, so we can directly use Controller class.

In theory, we might never need to override any of the default behavior but its always good to know that we have the power to do so. We get a default behavior but we can always change it according to our needs and preferences. 

Each controller has methods which map to specific actions and have a specific return type. In the next post, we will discuss Action Methods and Action Results.

Reference: "Professional ASP.NET MVC 5"

Thursday, January 1, 2015

MVC Features Old and New

This is my second post in the series of blog posts where I am talking about MVC 5.

MVC Features

Today I am going to discuss some of the features / components of MVC briefly that help us in building our dream web application.

Forms and HTML helper

MVC lets us exploit the power of Form tag & HTML Helpers help us establish coordination between a view and the run-time.

Data Annotation and Validation

Annotations allow us to feed metadata to the framework. This metadata is then used by framework for validations as well as in building the HTML to display and edit models.

Membership, Authorization and Security

MVC has bunch of features for authentication, authorization, enabling external logins and preventing attacks like SQL injection, cross-site scripting, cross-site request forgery, over posting, open redirection, etc.


Ajax techniques help you build responsive web applications which are necessary for good user experience. Using unobtrusive JavaScript. JQuery, JQuery UI etc make the client side programming easier and more powerful.


This helps you map logical URLs to controller action methods. Routing in itself can be considered as fourth component of MVC other than model, view and controller.


This is a package management system for .NET and Visual Studio. It makes it easy to add, update and remove external libraries and their dependencies in our application.


This allows the application to accept and generate structured data in form of XML, JSON, etc and allows us to dispatch actions based on HTTP verbs rather than actions.

Dependency Injection

Dependency Resolver in MVC allows the application to use dependency injection for services as well as controllers and view pages.

Unit Testing

Unit Testing capability is well integrated with the MVC application and guides us how to write unit tests for the application.

    Newly Added Features to MVC 5

    Furthermore, some of the new awesome features that are added to MVC 5 are:

    One ASP.NET

     In MVC5, when you create a project, only one ASP.NET project type exists. You can simply create a web application and later decide what type you want it to become, e.g. Web forms, MVC, etc.

    New Web Project Experience

    The dialogs for creating a new application have been simplified a lot in Visual Studio 2013.

    ASP.NET Identity

    The new ASP.NET identity system spans across the whole ASP.NET family whether its MVC, Web Forms or SignalR, etc.

    Bootstrap Templates

    In MVC5, the project templates use the well-known Bootstrap framework which gives the project a nice look and feel. You can easily customize the look and feel using any of the bootstrap themes or creating your own.

    Attribute Routing

    This is my favorite feature addition in MVC 5. This allows us to add routes to our controllers or action methods using data annotation. In my opinion, this gives clarity to the code and the routing in general.

    ASP.NET Scaffolding

    The new scaffolding system works across any ASP.NET application. You can also build your own scaffolder or edit the existing one if needed.

    Authentication filters

    In MVC5, we can have authentication filters at the controller and action level. This way we can secure only specific actions, if needed and we don't need to apply security at the whole application level.

    Filter Overrides

    This feature allows us to override a specific global filter for any particular action or controller.

    Reference: "Professional ASP.NET MVC 5"