首页 > 代码库 > 搜索,并且缓存搜索历史记录
搜索,并且缓存搜索历史记录
1、将关键字加入cookie缓存中
/// <summary>
/// 添加搜索关键字
/// </summary>
/// <param name="keyWord"></param>
private void addKeyWord(string keyWord)
{
keyWord = keyWord.Trim();
HttpCookie cook;
if (Request.Cookies["keyWordList"] == null)
{
cook = new HttpCookie("keyWordList");
cook.Expires = DateTime.Now.AddMonths(1);
}
else
{
cook = Request.Cookies["keyWordList"];
}
List<string> list = getKeyWord(HttpContext);
if (list.Contains(keyWord))
{
list.RemoveAll(p => p == keyWord);
}
if (list.Count >= 3)
{
list.RemoveAt(0);
}
list.Add(keyWord);
string productList = JsonConvert.SerializeObject(list);
cook.Value = http://www.mamicode.com/HttpUtility.UrlEncode(productList, Encoding.UTF8);
cook.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cook);
}
2、获取搜索关键字
/// <summary>
/// 获取搜索关键字
/// </summary>
/// <returns></returns>
public List<string> getKeyWord(HttpContextBase context)
{
HttpCookie cook = context.Request.Cookies["keyWordList"];
List<string> result = new List<string>();
if (cook == null)
{
return result;
}
else
{
JsonSerializer jserial = new JsonSerializer();
StringReader strread = new StringReader(HttpUtility.UrlDecode(cook.Value, Encoding.UTF8));
result = jserial.Deserialize<List<string>>(new JsonTextReader(strread));
}
return result;
}
3、在页面上渲染 调用
<div class="search">
<div class="demo-container demo">
<div class="search1">
@* <img src="http://www.mamicode.com/~/StoreWeb/Shop/images/searchInput.png" id="img" />*@
<input type="text" value="http://www.mamicode.com/@(keyWordlist.Count > 0 ? keyWordlist[0] :"")" id="searchInput" class="sinput" placeholder="请输入查找内容"/>
<a class="sbtn" href="javascript:;" id="search" title="搜索">搜索</a>
</div>
</div>
<div class="searchWork">
<p class="searchWorkList">
@{
foreach (var item in keyWordlist)
{
<span>@item</span>
}
}
</p>
</div>
</div>
搜索,并且缓存搜索历史记录
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。