Reputation: 99
I am newer to MVC3 and have a controller with one action.I defined some global properties in controller class and assigned values to those properties in action method. ex:
public class RosterController : Controller
{
int var1;
int var2;
int var3;
public ActionResult Index(int param1)
{
if(param1 ==1)
{
return view(newRosterViewModel(var1+1,var2+2,var3+3));
}
else
{
var1=1;
var2=2;
var3=3;
return view(newRosterViewModel(var1,var2,var3));
}
}
}
In this code first time assigning values to var1
,var2
,var3
. second time I need those vaues but values are null.
I tried with TempData but that also not holding value.
Upvotes: 2
Views: 250
Reputation: 108975
but values are null.
I think you'll find their values are 0 (zero), this is the default value for integral fields.
Every request mapped to RosterController
will cause a new instance of RosterController
to be created, this avoids any issues with concurrent requests mixing up their controller state.
To persist information from one request to another there are many options (database, Session, cookies, Application, …), but the state of a controller instance is not one of them. The right approach to persistence across requests depends on the requirements.
Upvotes: 2
Reputation: 26930
When you render view you should pass this variables to controller again, because on every request controller is recreated:
public class RosterController : Controller
{
int var1 = 0;
int var2 = 0;
int var3 = 0;
public ActionResult Index(int param1, int var1, int var2, int var3)
{
if(param1 ==1)
{
return view(newRosterViewModel(var1+1,var2+2,var3+3));
}
else
{
var1=1;
var2=2;
var3=3;
return view(newRosterViewModel(var1,var2,var3));
}
}
}
Upvotes: 0
Reputation: 47774
You can make your variables static. Making your variables static means - thier lifetime extends across the entire run of the program.
declare static like this
private static int var1;
private static int var2;
private static int var3;
But first please tell us your exact Use case
Upvotes: 1
Reputation: 20674
Why not make them static?
private static int var1;
or use Cache or Session
HttpRuntime.Cache.Add("var1", value);
var var1= HttpRuntime.Cache.Get("var1");
Upvotes: 1