Because you're not persisting the value anywhere.
HTTP is stateless. What this means in ASP.NET is that each HTTP requests results in a new instance of the controller being requested. So the following sequence of events is happening here:
- User makes a request to
SetCustomer
, creating a new instance of the class
- Value is stored in a class-level variable
- Request is responded to and completed, the instance of the class is destroyed
- User makes a request to
Index
, creating a new instance of the class
Since it's a new instance, no value is set. There are a variety of places you can store data, it just has to be in a context that both requests can access. Examples, in no particular order, include:
- Database
- Session
- URL query string
- Cookie
- etc.
Basically, you have to write the value to some location which persists between requests. In-memory variables don't do that in web applications.
A simple example here could be to include the value on the query string in the redirect. In ASP.NET MVC, that might look something like this:
return RedirectToAction("Index", new { customer_id = id });
What this would do is include on a URL parameter a customer_id
value when the user is redirected. So your Index
action you could accept that parameter:
ActionResult Index(int? customer_id = null)
{
// use the customer id if one is provided
}
In this case I assumed that the value should be nullable in case the Index
is ever requested without a value. But what you prefer to do for that is up to you. Basically this action now has an optional parameter, which you would use however you're currently trying to use it.
The benefit of this is that it maintains the intended statelessness of web applications. You're storing the state (the customer_id
value) in the request/response itself, as opposed to some other medium (session, database, etc.) where you become responsible to maintaining it.