I have some repetitive ViewData
data that I need them in several controllers
. I'd like to create a utility function for that. I'm trying to have an out
parameter and call the function with controller's ViewData
.
Can someone please guide about the correct syntax and approach to do this?
public static void GetSheetsEssentialViewData(out ViewDataDictionary ViewData)
{
ViewData["111"] = Utility.111();
ViewData["22"] = Utility.22();
ViewData["33"] = Utility.33();
.....
}
You're getting an error because an out
parameter has to be initialized in the method before you use it - it's initially unassigned. However, I don't think you want it to be an out
parameter at all.
You can just pass the existing reference from the controller, not using an out
parameter at all:
// In UtilityClass
public static void GetSheetsEssentialViewData(ViewDataDictionary viewData)
Then in a controller method:
UtilityClass.GetSheetsEssentialViewData(ViewData);
Or you might consider making it an extension method:
public static void PopulateSheetsData(this ViewDataDictionary viewData)
Then you in your controller you can just call it with:
ViewData.PopulateSheetsData();
which is very readable, IMO.
(To find out more about ref
and out
parameters, you might want to read my article about C# parameter passing.)
See more on this question at Stackoverflow