Wednesday, December 9, 2015

How to Read Rout optional parameter in null parameter Action Method in a Controller in MVC ?

By default, the values for action method parameters are retrieved from the request's data collection. The data collection includes name/values pairs for form data, query string values, and cookie values.
The controller class locates the action method and determines any parameter values for the action method, based on the RouteDatainstance and based on the form data. If the parameter value cannot be parsed, and if the type of the parameter is a reference type or a nullable value type, null is passed as the parameter value. Otherwise, an exception is thrown.
There are several ways to access URL parameter values in the action methods of controller classes. The Controller class exposesRequest and Response properties that can be accessed in an action method. These properties have the same semantics as theHttpRequest and HttpResponse objects that are already a part of ASP.NET. However, the Request and Response objects of theController class accept objects that implement the HttpRequestBase and HttpResponseBase abstract classes instead of being sealed classes. These base classes make it easy to create mock objects, which in turn makes it easy to create unit tests for controller classes.
The following example shows how to use the Request object to retrieve a query-string value named id.
public void Detail()
{
    int id = Convert.ToInt32(Request["id"]);
}

No comments:

Post a Comment