我对MVC和ASP.NET的概念相当陌生,我想知道是否有可能为我的模型创建一次对象并在不同的视图中使用它。
我正在编写一个通过web服务调用获取JSON对象的应用程序,该调用包含要填充的所有信息。web服务调用需要一个ID来创建正确的JSON对象。由于JSON对象相当大,所以web服务调用需要大约2秒的时间来下载JSON对象。每次切换视图时都会生成模型(包括下载JSON对象),这会增加巨大的开销。
为不同视图生成不同的视图模型不起作用,因为下载是瓶颈。
有什么办法解决这个问题吗?下载的JSON字符串可以以某种方式存储在不同的视图中吗?如果ID更改,是否可以仅下载JSON对象?
问候
发布于 2016-03-01 07:02:51
这样的东西会起作用的:
public ActionResult MyView(int someId)
{
string json = this.GetJson(someId);
var model = new MyViewModel(json);
return this.View(model);
}
private string GetJson(int id)
{
string cacheKey = "myJsonCacheKey" + id;
string cachedJson = this.HttpContext.Cache[cacheKey] as string;
if (cachedJson != null)
return cachedJson;
string actualJson = new WebClient().DownloadString("http://whatever");
this.HttpContext.Cache.Insert(cacheKey, actualJson);
return actualJson;
}只需注意两点:
HttpContext.Cache,代码将非常相似。https://stackoverflow.com/questions/35715381
复制相似问题