Making namespace available across all MVC Razor views

If you are intending to use the same namespace across multiple views, just include it in the web.config of the Views folder. In the following example I wanted the MyProject.WebUI.Properties namespace to be available to all views. The removes the need to add the using statement for this namespace to every view. Please note, once you’ve added the namespace you’ll need to close and reopen any open view files for intellisence to recognize the namespace.

    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="MyProject.WebUI.Properties" />

Rename cookie

You can adjust it in your web.config file, the default is ASPXAUTH:

   <authentication mode="Forms">
      <forms name=".CRM-Cookie" loginUrl="LoginPage.aspx" />

This is useful when running multiple applications from the same server under the same domain. CheckBoxList validation

A custom validator can be used to validate a CheckBoxList control. However its crucial the correct attributes are passed. The most common mistake is using the ControlToValidate in CustomValidator. By using this you encounter the following:


Instead just use the OnServerValidate attribute to point to a validation method in the code behind. In this method create a reference to CheckBoxList control and run any validation required.

MVC Ajax Sys is undefined message

I spent an entire day trying to figure out why my Ajax.Begin form helper was failing to update the target div container. By chance I noticed the Sys is undefined message flash past in the Chrome console window. I’ve seen this before with Ajax enabled websites and it usually points to the project not being configured to use Ajax correctly. The jquery.unobtrusive-ajax package has been installed through NuGET correctly but it hadn’t set the configuration correctly.

Make sure the jquery.unobtrusive-ajax.js file is loaded after jquery and <add key=”UnobtrusiveJavaScriptEnabled” value=”true” /> in included in the web.confg <appSettings> section.

C# Virtual Methods

A vertical method can be redefined in derived (class which inherit from this) classes. A virtual method has an implementation in both the base and derived class. These methods are used when the base class provides the required functionality most of the time, but may need changing by a derived class on occasion. A virtual method can be redefined by the derived class using the override keyword with the same method name. Methods which are not defined as virtual cannot be overriden in a derived class and must use the functionallity provided in the base class.

Example – Both the Rectangle and Circle classes inherit from the Shape class. However has the area of a circle is calculated differently to a rectangle, the circle class overrides to Area method. As the Colour method isn’t virtual both derived classes have to use the same method so in this case both will be red.

class Shape
	public string Colour()
		return "Red";
	public virtual double Area(double width, double height)
		return width*length;

class Rectangle : Shape
	public Rectangle()
		string colour = Colour();
		double width = Area(10.5,15);
class Circle : Shape
	public Circle()
		string colour = Colour();
		double width = Area(15);
	public override double Area(double radius)
		return 3.141*raduis*2;

MVC Creating a Default Error Handler for a Controller

All you have to do to create a default error handler for your ASP.NET MVC controller is put the HandleError attribute on the class. Then, if your code throws an unhandled exception (one not caught in the Try…Catch block), the user will be sent the default Error View in the Views/Shared folder:

Public Class HomeController Inherits System.Web.Mvc.Controller

At least that’s what the attribute will do if you have this tag inside the system.web element in your web.config file:

<customErrors mode=”On” defaultRedirect=”Error”/>

You can add whatever error information you want to the default Error View by adding code to the View that writes out properties from the Model’s Exception property. Alternatively, setting the customErrors element’s mode to RemoteOnly will, when you’re debugging, let you continue to see ASP.NET’s default error page with all of its information while still sending the Error View to your users in production.

MVC ViewData / ViewBag / TempData / Session


1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
2. ViewData is used to pass data from controller to corresponding view.
3. It’s life lies only during the current request.
4. If redirection occurs then it’s value becomes null.
5. It’s required typecasting for getting data and check for null values to avoid error.


1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
2. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
3. It’s life also lies only during the current request.
4. If redirection occurs then it’s value becomes null.
5. It doesn’t required typecasting for getting data.


1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
2. TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
3. It’s life is very short and lies only till the target view is fully loaded.
4. It’s required typecasting for getting data and check for null values to avoid error.
5. It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article: Persisting Data with TempData


1. Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it never expires.
2. Session is valid for all requests, not for a single redirect.
3. It’s also required typecasting for getting data and check for null values to avoid error.

MVC HiddenFor not getting correct value from model

When assigning a value to a HiddenFor html helper MVC will always use the first value posted. So if the value is then updated during a post back like below, the browser will still display the original value.

public ActionResult Foo(SomeModel model)
    model.CurrentStep = Steps.SomeNewValue; // CurrentStep is the HiddenFor value
    return View(model);

There are two solutions.

1. Clear the model state for the HiddenFor value before assigning the new value:

public ActionResult Foo(SomeModel model)
    model.CurrentStep = Steps.SomeNewValue;
    return View(model);

2. Manually generate the hidden field

<input type="hidden" name="NextStep" value="<%= Model.CurrentStep %>" />