Rename ASP.net cookie

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

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

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

ASP.net 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:

validationerror

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;
	}
}

What is dependency injection 

A simple definition is:

Dependency Injection is where components are given their dependencies through their constructors, methods, or directly into fields.

For example a class constructor creates an instance of an object. This class is now dependant on that object. If however this object is passed into the constructor this dependancy is decoupled.

For dependancy injection to work correctly each class requires an interface. This will ensure if the object is switched it will still present the same methods, it doesn’t however need to know what these methods do.

Unit testing as one of the main uses for dependancy injection. It allows objects which perform complex data processing tasks to be replaced with an object which provides mock data for testing. The class being tested doesn’t care how this data is created as long as it’s presented in the same format.

Another example is an object provided SQL database access methods. Using dependancy injection we can switch this to another object with MySQL access methods. As long as both objects expose the same methods the objects using them won’t care which one it is.

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:

<HandleError>
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

ViewData

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.

ViewBag

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.

TempData

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

Session

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.

[HttpPost]
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:

[HttpPost]
public ActionResult Foo(SomeModel model)
{
    ModelState.Remove("CurrentStep");
    model.CurrentStep = Steps.SomeNewValue;
    return View(model);
}

2. Manually generate the hidden field

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