ASP.NET MVC – Some important and interesting facts to note..

I was going through a course in ASP.NET MVC and I noted down some important and interesting facts to keep in mind. Thought of sharing…

Adding a Bootstrap theme

What is Bootstrap? Basically Bootstrap is a free front-end framework with HTML and CSS that allows your website to be faster, easier and be adjusted to any device in which it may be viewed.

So if you want to change the default bootstrap theme and add a new one to your ASP.NET MVC web site, go to in your browser and click on the ‘Themes’ drop down from the upper navigation bar. Select a theme you would like and you will be able to see the styles that will be applied with each theme.


As shown in the image above I have selected the theme ‘superhero’ for the purpose of this blog. The Navigation bar and the buttons of the superhero theme would look like this.

In order to save the theme to your application, click the button with the selected theme name on the top navigation bar and select ‘bootstrap.css’ and you will see the bootstrap.css file with the modified styles of the selected theme. You can right-click and save the file to your project’s ‘Content’ folder. Remember to give a unique name to the new css file. e.g – bootstrap-superhero.css.


Now it is time to apply the new css file to the application. Open the file ‘BundleConfig.cs’ from the ‘App_Start’ folder. This file is used to define different bundles for client side assets. The usage of bundling is to compress two or many files (e.g – multiple javascript files) together, so it would reduce the number of Httprequests made to get these resources. As you can see from the below image a StyleBundle have been added to the bundle and the ‘bootstrap.css’ file has been used by default. Now change the name of of the css file to bootstrap-superhero.css.


Build the application and run. Now you will be able to see the new theme in action.



Action Result types in ASP.NET MVC

In a MVC app, methods of the Controller are called ‘Actions’ and returns an object of type ‘ActionResult’. ‘ActionResult’ is the base class for all the types we are going to mention here. To return the ActionResults, each of them have a corresponding helper method inherited from the ‘System.Web.Mvc.Controller’ class. Lets look at some ActionResults of MVC.

  • ActionResult Type – ViewResult -> Helper Method – View()
  • ActionResult Type – PartialViewResult -> Helper Method – PartialView()
  • ActionResult Type – ContentResult -> Helper Method – Content()
  • ActionResult Type – RedirectResult -> Helper Method – Redirect()
  • ActionResult Type – RedirectToRouteResult -> Helper Method – RedirectToAction()
  • ActionResult Type – JsonResult -> Helper Method – Json()
  • ActionResult Type – FileResult -> Helper Method – File()
  • ActionResult Type – HttpNotFoundResult -> Helper Method – HttpNotFound()
  • ActionResult Type – EmptyResult -> Helper Method – In this case only you have to return a new instance of EmptyResult() (new EmptyResult())


Action Parameter Binding

When a request is received to the application, MVC automatically maps the request data to parameter values of the specific Action method: if both parties have a request data field/parameter with the same name, they are automatically mapped. Generally there are three ways trough which request data can be passed: 1. As a part of the URL (e.g – students/edit/1), 2. As a query string (e.g – students/edit?id=1) and 3. Submit with the form data (e.g – id=1). In all these scenarios, ‘edit’ action accepts an integer parameter named ‘id’.

There is something called the ‘default action parameter’, which is declared in the ‘RouteConfig’ file located in the ‘App_Start’ folder.


In the image above the default routing URL of the application is defined and the highlighted field is the default parameter name. If someone is passing the request data as a part of the URL (e.g – students/edit/1), the parameter name of the ‘edit’ action must be ‘id’ (public ActionResult edit(int id)). This constraint is not applicable for action parameter binding when passed using the other two methods mentioned above.

A parameter can be declared as an optional parameter, so when that specific action is invoked, sending request data is not a must. In order to achieve this, the parameters should be nullable.


In here string does not need to be declared as nullable, since it is a reference type and by default nullable. When this action is invoked by the url ‘…students/index’, no errors would be displayed, and the method would be executed, just like when parameters are passed.


Custom Routes

As mentioned earlier, the default routing URL is declared in the ‘RouteConfig’ file located in the ‘App_Start’ folder. Even though this works absolutely fine in most scenarios, there can be some situations where it is required to have more than one parameter to be passed (e.g – to get the list of students enrolled in the first month of 2010 – students/enrolled/2010/1). To do that a new custom route needs to be declared.




Remember to place the more specific custom routes before the more generic default route, otherwise the more generic route will be in action.

Now we have to declare the action to match the custom route.


Moreover, we can have constraints on the parameters; for example the year should be four digits and the month should be to digits. Let’s see how this can be achieved.


The ‘MapRoute’ method accepts another argument to declare the constraints. Here I have used regular expressions to do so. The year accepts four digits and the month accepts 2 digits. Now you cannot invoke this action by ‘students/enrolled/2010/1’, this will give a 404 error. You have to use ‘students/enrolled/2010/01’.


Attribute Routing

The mechanism of custom routing has some disadvantages: with bigger companies, the number of custom routes that needs to be declared can be unmanageable and also if an action name/parameter name is changed, it needs to be changed in the route as well. There is an easier way to declare customized routes: ‘Attribute Routing’.

First you have to enable attribute routing; in order to do that, just after the code line ‘routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);’ add the code ‘routes.MapMvcAttributeRoutes();’.


Note – remember to delete any custom routes that you have had declared for the same specific action to which you want to have a custom route.

Now in the action, apply the route attribute and pass the URL template. As you can see from the below image, you can also define any constraints. As an example I have restricted the month to be only 2 digits (here since the regular expression is not a verbatim string, you have to have double slashes) and to have a value ranging from 1 to 12.


There are many other constraints that you can declare in the ‘Route’ attribute:

  • min
  • max
  • minlength (for strings)
  • maxlength (for strings)
  • int
  • float
  • guid


Passing data to the View

There are three ways to pass data to the View. As my initial approach I have used the below method of passing the ‘Student’ object to the view, via the ‘View’ helper method. In here, the student object is actually assigned to the ViewData.Model object of the ViewResult. (var viewReult = new ViewResult(); viewReult.ViewData.Model = student;). The ‘ViewData’ mentioned here is not a regular dictionary, it can be used as a normal dictionary with key-value pairs as well as we can use its ‘Model’ property.


To access this ‘Student’ object from the View, you have to have the following code:


As you can see from the highlighted code, it is required to define the type of the model to ‘Student’ type, otherwise you will not be able to access the properties of the student.

The second method is to use the ‘ViewData’ dictionary. This property is available for every Controller.


The ViewData object stores items of type ‘Object’, therefore you can have any name and add the student object. Remember to remove the any arguments from being passed in to ‘View’ method.


This is how, the student object can be accessed from the View, and the coding is a little bit tricky. Since the ‘ViewData’ dictionary contains objects, it is not possible to access the student object properties without casting. Now it is obvious that you have to write more tricky coding than the first approach and also if the name you have given when adding our student object to the ViewData dictionary changes in the controller, it is a must to change that in the View as well.

The third approach is similar to the previous one: usage of ‘ViewBag’, which is a dynamic type. (dynamic is a static type that acts like a placeholder for a type not known until run time.) Just like the ‘ViewData’, you can give any name to the object. Since the ViewBag is of type dynamic, our object will only be added at the run time and therefore no compile time safety. With this approach also the same set of issues exists as mentioned above. So in my opinion the first approach is the best and easiest.



Usage of ViewModels

Imagine a situation where it is required to pass more than one object to the View. Only one object can be assigned to the Model. As a solution for this we create a  new type of class called a ‘ViewModel’. A ViewModel defines data and rules specific to a View.


A new folder named ‘ViewModel’ was created and inside that a class called ‘RandomViewModel’ was added for the View named ‘Random’. As a naming convention, with the View’s name add the post-fix ‘ViewModel’.

(I created a ‘Module’ object and mapped that here as one student taking several modules).

Now create the RandomViewModel object in the Controller and pass that to the View instead of the single Student object.


From the View you can access the ViewModel object as follows:


Instead of the model being of type Models.Student object, now it is of the RandomViewModel type. From the Model, accessing the Student object is pretty straightforward. To print the modules list, I have used a foreach loop. It is compulsory in ASP.NET MVC to add curly braces in the code block (declared after the @ sign). Inside the code block, it is possible to write either C# code or HTML. The view engine in MVC called Razor View Engine knows how to parse them.

One final tip before I end this blog; you can type the shortcut ‘mvcaction4’ and press tab to create an action without typing the code stub manually.

I hope this simple blog will help someone. Thank you for reading.

hope for the best!!