Reputation: 1762
in this Code
public ActionResult Index(int? id)
{
return View();
}
What does the int? id
do?
Can we write it in this format also?
public ActionResult Index()
{
int id;
return View();
}
Upvotes: 1
Views: 5301
Reputation: 28737
It allows you to pass a parameter to the Action.
If you have a route specified like this:
"{controller}/{action}/{id}"
Then you will be able to call the URL YourController/Index/1
and the 1
will be passed into your action.
The question-mark after the int
means that it is a Nullable<int>
aka it is an optional parameter. If it's not in the URL the id will be null
Your alternate syntax does not work.
Upvotes: 6
Reputation: 218702
Id
is a parameter of your Index action method. With the default route definitions, When a request comes for your Index action method ,the part of your url(URL segment) which has the value for your Id param will be mapped to the Id
param of your Action method.
For example, for the request yourSiteName.com/yourControllerName/Index/350
, your Index action method will be executed and 350
will be available in the Id
parameter and will be accessible inside your method.
int?
means it is nullable int which means the value can be null.When you do not provide value for a nullable int parameter, It will be NULL.
In terms of MVC routing, this means that the action method can be accessed like yourControllerName/Index
and yourControllerName/Index/23
,with the default route definition. Sometimes people use this to return a List/Index view for the request without the Id value and return a specific item for the request with the Id passed in.
So before accessing the value, you should check whether it is null or not. If it is not null, you may use the Value property to get the value stored inside the param.
public ActionResult Index(int? id)
{
if(id!=null)
{
//request came with a value for id param. Let's read it.
var idValue =id.Value;
//do something with the IdValue which is an Int
}
else
{
//request came without a value for id param
}
return View();
}
Upvotes: 4