如何解决存储 AJAX 结果 MVC .Net Core
我有下面的<script>
$(function () {
$("#validateBtn").click(function () {
var userkeyInput = $("#UserKeyInput").val();
var EmailInput = $("#EmailInput").val();
$.ajax({
url: "@Url.Action("ValidateUser")",data: { UserKey: userkeyInput,Email: EmailInput },type: "GET",contentType: "application/json; charset=utf-8",dataType: "json",success: function (result) {
if (result.success == true) {
$("#verificationTab").hide();
$("#setpasswordTab").show();
var userKey = result.userKey; // This is the UserKey of the user.
var headertext = document.getElementById("TabHeaderText2");
headertext.innerHTML = "Verified";
}
else {
var headertext = document.getElementById("TabHeaderText1");
headertext.innerHTML = result.error;
}
},error: function (result) {
window.alert("This is an unhandled exception. ");
}
});
});
});
此 AJAX
以 Json 形式获取结果。验证完成后,我丢失了从 AJAX 收到的数据。验证完成后,我需要该数据用于其他功能。我怎样才能方便地保存这些数据?我应该在服务器端使用 Tempdata
吗?
控制器
public IActionResult ValidateUser(string UserKey,string Email)
{
return Json(new { success = false,data="this is the data that i want to save somewhere"});
}
解决方法
验证完成后,我丢失了从 AJAX 收到的数据。 验证完成后,我需要该数据用于其他功能。如何 我可以把这些数据放在手边吗?我应该在服务器端使用 Tempdata 吗?
您可以将数据存储在服务器端或客户端。在服务器端,您可以使用 Session 来存储记录。在客户端,您可以使用 HTML Web Storage 来存储数据。
要在 asp.net 核心应用程序中使用 Session,Startup.cs 必须包含:
- 任何 IDistributedCache 内存缓存。 IDistributedCache 实现用作会话的后备存储。有关详细信息,请参阅 ASP.NET Core 中的分布式缓存。
- 在 ConfigureServices 中调用 AddSession。
- 在 Configure 中调用 UseSession。
代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); //remember check the session expired time,by default it is 10 seconds.
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
}
然后,要使用会话来存储对象类型数据,我们应该创建一个 SessionExtensions.cs 文件并包含以下代码:
//required using Microsoft.AspNetCore.Http;
//required using System.Text.Json;
public static class SessionExtensions
{
public static void Set<T>(this ISession session,string key,T value)
{
session.SetString(key,JsonSerializer.Serialize(value));
}
public static T Get<T>(this ISession session,string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
之后,参考以下代码从会话中存储/获取数据:
List<UserViewModel> items = new List<UserViewModel>();
// check if session exist
if (HttpContext.Session.Get<List<UserViewModel>>("userdata") != default)
{
//get the stored data from the session
items = HttpContext.Session.Get<List<UserViewModel>>("userdata");
}
items.Add(model);
//store the latest data in the session
HttpContext.Session.Set<List<UserViewModel>>("userdata",items);
HTML 网络存储提供了两个用于在客户端存储数据的对象:
- window.localStorage - 存储没有到期日期的数据
- window.sessionStorage - 存储一个会话的数据(关闭浏览器选项卡时数据丢失)
网络存储的使用如下:
//check if browser support Web storage.
if (typeof (Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// Store
localStorage.setItem("data","Smith");
// Retrieve
var data = localStorage.getItem("data");
} else {
// Sorry! No Web Storage support..
}
最后,您可以参考以下示例代码,使用 JQuery Ajax 在 Asp.net Core 中存储数据。
型号:
public class UserViewModel
{
public string userkey { get; set; }
public string Email { get; set; }
}
HomeController.cs(在ValidateUser方法的头部添加HttpPost属性):
public IActionResult Index2()
{
List<UserViewModel> items = new List<UserViewModel>();
// check if session exist,and then get data from session.
if (HttpContext.Session.Get<List<UserViewModel>>("userdata") != default)
{
items = HttpContext.Session.Get<List<UserViewModel>>("userdata");
}
return View(items);
}
[HttpPost]
public IActionResult ValidateUser(UserViewModel model)
{
List<UserViewModel> items = new List<UserViewModel>();
// check if session exist
if (HttpContext.Session.Get<List<UserViewModel>>("userdata") != default)
{
//get the stored data from the session
items = HttpContext.Session.Get<List<UserViewModel>>("userdata");
}
items.Add(model);
//store the latest data in the session
HttpContext.Session.Set<List<UserViewModel>>("userdata",items);
return Json(new { success = true,data = items });
}
查看(Index2.cshtml):
@model IEnumerable<WebApplication.Models.UserViewModel>
@{
ViewData["Title"] = "Index2";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.userkey)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.userkey)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit","Edit",new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details","Details",new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete","Delete",new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="UserKeyInput" class="control-label">User Key</label>
<input id="UserKeyInput" class="form-control" />
</div>
<div class="form-group">
<label for="EmailInput" class="control-label">Email</label>
<input id="EmailInput" class="form-control" />
</div>
<div class="form-group">
<input type="button" value="Create" id="validateBtn" class="btn btn-primary" />
</div>
</div>
</div>
在Index2.cshtml页面的最后,使用如下脚本向控制器提交数据:
@section Scripts{
<script>
$(function () {
$("#validateBtn").click(function () {
var UserViewModel = {}; //create an object
UserViewModel.userkey = $("#UserKeyInput").val();
UserViewModel.Email = $("#EmailInput").val();
$.ajax({
url: "@Url.Action("ValidateUser")",data: { model: UserViewModel },//the name ("model") should be the same with the parameter's name in the controller.
type: "Post",//change the method to Post.
success: function (result) {
if (result.success == true) {
console.log(result.data);
if (typeof (Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
sessionStorage.setItem("userdata",JSON.stringify(result.data));
} else {
// Sorry! No Web Storage support..
}
}
else {
alert("fail");
}
location.reload(); //refresh the current page
},error: function (result) {
window.alert("This is an unhandled exception. ");
}
});
});
});
</script>
}
结果如下(打开F12开发者工具,在Application面板中可以找到web storage):
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。