Reputation: 9247
I have RegisterModel
and i need to set default value for SelectCountryID
and in controller pass that value but when i do like this i get an error :
"Object reference not set to an instance of an object."
public class RegisterModel
{
public RegisterModel()
{
SelectCountryID=1;
}
public int SelectCountryID {get;set;}
}
Controller:
int test = Model.Register.SelectCountryID;
EDIT:
IndexPageModel model = new IndexPageModel();
model.Register = new RegisterModel
{
int test = model.Register.SelectCountryId,
Country = new SelectList(manager.GetCountries(), "Id", "Name"),
WebTypeOfLicense = new SelectList(CommonDbService.GetAllLicense(), "Id", "Name"),
Region = new SelectList(manager.GetRegions(model.Register.SelectCountryId), "Id", "Name"),
};
Upvotes: 0
Views: 5275
Reputation: 30607
The problem is in the way you instantiate your model.
model.Register = new RegisterModel{...}
This will execute what is in between the {}
before calling the constructor. Also, you cannot define new variables within the braces like
{int test = model.Register.SelectCountryId,...}
In the controller, you need to create a new instance of the model like
RegisterModel model = new RegisterModel();
int test = model.SelectCountryID;
Upvotes: 1
Reputation: 3019
you an use system.ComponentModel.DefaultValue attribute
[System.ComponentModel.DefaultValue(0)]
public int SelectCountryID { get; set; }
Upvotes: 3