[英]Use MVC Session to store Client-side values (e.g. filter text) between visits
In an MVC View, is there an efficient way to store client-side values for use on subsequent page visits? 在MVC视图中,是否有一种有效的方法来存储客户端值以供后续页面访问使用?
Typical scenario 典型场景
An Index page has a table that's getting a bit long so I add a filter (I know paging is another option) and use an input control with some JavaScript to limit the table rows without having to perform another "Get" from the server. 索引页的表有点长,所以我添加了一个过滤器(我知道分页是另一个选择),并使用带有一些JavaScript的输入控件来限制表行,而不必从服务器执行另一个“获取”。
This works fine but, if I navigate off (say) into an edit page then return back to the Index page, the filter is clearly no longer there. 效果很好,但是,如果我导航(例如)进入编辑页面,然后返回到“索引”页面,则过滤器显然不再存在。
After a bit of searching I never found anything simple so I post my meagre answer below. 经过一番搜索之后,我再也没有发现任何简单的东西,因此我在下面发布了我的微薄答案。
The View contains a form at the top of the page into which a user can type filter text (on form "Get", text is set from a session value):- 视图在页面顶部包含一个表单,用户可以在其中输入过滤器文本(在“获取”表单上,文本是通过会话值设置的):
<form id="frmEdit">
@Html.AntiForgeryToken()
<div class="form-group row">
<div class="col-sm-6">
@Html.ActionLink("Create New", "Create", null, new { @class = "nav-item nav-link" })
</div>
<label for="search" class="col-sm-2 col-form-label text-right">Filter</label>
<div class="col-sm-4">
<input type="text" placeholder="Filter" class="form-control" id="search" value=@Session["SparesSectionFilter"]>
</div>
</div>
</form>
A script section contains the filtering JavaScript but also a postback to the controller 脚本部分包含过滤的JavaScript以及回发到控制器的信息
@section Scripts{
<script type="text/javascript">
// on load
PerformFilter();
// hook up events
$(function () {
$("input#search").on("keydown keyup", function () {
PerformFilter();
// post back to session for reuse
$.post('SparesSections/Session_Add', { __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(), itemName: 'SparesSectionFilter', itemValue: $("#search").val() });
});
})
</script>
}
I have a custom base-class for my controller into which I've added the following actions. 我为控制器自定义了一个基类,并在其中添加了以下操作。 These are usable from any controller using this class.
这些可从使用此类的任何控制器使用。 The Razor view loads the session value but I've included a "Get" in the controller for client-side options.
Razor视图加载了会话值,但是我在控制器中为客户端选项添加了“ Get”。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Session_Add(string itemName, string itemValue)
{
Session.Add(itemName, itemValue);
return Json(new { itemName = itemName, itemValue = itemValue }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Session_Get(string itemName)
{
return Json(new { itemName = itemName, itemValue = Session[itemName] ?? string.Empty }, JsonRequestBehavior.AllowGet);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.