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 = 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="~/StoreWeb/Shop/images/searchInput.png" id="img" />*@
<input type="text" value="@(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>