I have anonymous type variable which i am populating like that(i have two variables jsonDataCache and jsonData but i want to have just one, jsonData for example) :
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from b in myData
select new
{
//do things
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
But if i want to define this variable first, before i do populate that, basically i want to do something like that:
var jsonData = null;
//check if jsonData in cache and if it is return Json(jsonData, JsonRequestBehavior.AllowGet);
jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from b in myData
select new
{
//do things
}).ToArray()
};
//put jsonData in cache by key
return Json(jsonData, JsonRequestBehavior.AllowGet);
How could i do that?
The reason i want to do that because i want to introduce the cache, so i need to define the variable first ant than check that in cache and if it is not i will do the thing above.
Currently i did that with two variables, bot i want to use just one.
Here is how i currently done that:
public virtual JsonResult GetSomething(int id, int type)
{
string keyPrefix = GetKeyPrefix(id, type);
var jsonDataCache = CacheManager.Get<object>(keyPrefix);
if(jsonDataCache != null)
return Json(jsonDataCache, JsonRequestBehavior.AllowGet);
var myData = GetFromDataase();
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from b in myData
select new
{
//do things
}).ToArray()
};
CacheManager.Set<object>(keyPrefix, jsonData);
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
UPDATE:
After all your help I think it should be something like that, hopefully it is right way to go:
public virtual JsonResult GetSomething(int id, int type)
{
string keyPrefix = GetKeyPrefix(id, type);
var jsonData = CacheManager.Get<object>(keyPrefix);
if(jsonData != null)
return Json(jsonData , JsonRequestBehavior.AllowGet);
var myData = GetFromDataase();
jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from b in myData
select new
{
//do things
}).ToArray()
};
CacheManager.Set<object>(keyPrefix, jsonData);
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
You can’t do that (and initialize to null), except for some really nasty and ugly “by example” tactics with generic methods. Variables to anonymous types can only be declared alongside initialisation (except as a generic type parameter).
It does, however, seem unlikely that you really need it here. Indeed,
would suffice, since you never use the value. Beyond that, I’d argue that it is time to introduce a DTO class for the purpose instead.