Saturday, December 15, 2012

Asp.Net MVC: Default parameters in action methods

In this article we will simplifies case of default parameter of action methods. These can be possible in 2 ways.

1. Using default value attribute:

The Default Value attribute of System.Componetmodel namespace lets you specify a parameter value which was not container in route values and action method will use that default value.

Public ActionResult  DoStuff(string  name, [DefaultValue(MyEnum.Alpha)] MyEnum enumToUse)
{
//Your Code Here
}

2. Using optional parameter in C# 4.0:

To pass default value in action method, we can also use C#4.0 optional parameter feature.

Public ActionResult  DoStuff(string  name, MyEnum enumToUse=myEnum.Alpha)
{
//Your Code Here
}

We can use both ways to pass default value, but if we are thinking about performance then, need to use second options because, Default value attribute will involve some reflection. I hope this will help you.