I have a selectListItem in a controller that I use to populate a dropdownlist.
public List<SelectListItem> BankSelectList()
{
List<SelectListItem> Region = new List<SelectListItem>()
{
new SelectListItem { Text = "" , Value = "",Selected = true},
new SelectListItem { Text = "North" , Value = "North"},
new SelectListItem { Text = "East" , Value = "East"},
new SelectListItem { Text = "North East" , Value = "North East"},
new SelectListItem { Text = "West" , Value = "West"},
};
return bank;
}
Is there a way I can reuse this in a different controller without needing to declare the list again in the other controller? I dont want to go to each controllers to update in case there are any changes in the future. I dont put it in database because the probability of changes are low, and Im also trying to save on performace.
CodePudding user response:
Use the static class :
public static class DataStaticSelectList
{
public static List<SelectListItem> BankSelectList()
{
List<SelectListItem> Region = new List<SelectListItem>()
{
new SelectListItem { Text = "" , Value = "",Selected = true},
new SelectListItem { Text = "North" , Value = "North"},
new SelectListItem { Text = "East" , Value = "East"},
new SelectListItem { Text = "North East" , Value = "North East"},
new SelectListItem { Text = "West" , Value = "West"},
};
return bank;
}
}
And in your Controller to access the data :
var selectList = DataStaticSelectList.BankSelectList() ;
CodePudding user response:
As mentioned above a static class could work. You could also make a seperate class that provides you with the required SelectListItem collection via a specific method. This potentially opens the option to use DI and populate the contents via whatever dataset your using.
public List<SelectListItem> GetBankSelectList()
{
return new List<SelectListItem>()
{
new SelectListItem { Text = "" , Value = "",Selected = true},
new SelectListItem { Text = "North" , Value = "North"},
new SelectListItem { Text = "East" , Value = "East"},
new SelectListItem { Text = "North East" , Value = "North East"},
new SelectListItem { Text = "West" , Value = "West"},
};
}