Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

Storing AJAX results MVC .Net Core

I have the <script> below

        $(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. ");

                }
            });

        });

    });

this AJAX gets the results in Json. After verification is done I lose the data that I received from AJAX. I need that data for other functions after verification is done. How can I keep that data handy? Should I use Tempdata on the server side?

controller

    public IActionResult ValidateUser(string UserKey,string Email)
    {

      return Json(new { success = false, data="this is the data that i want to save somewhere"});
    }

            
question from:https://stackoverflow.com/questions/65864969/storing-ajax-results-mvc-net-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After verification is done I lose the data that I received from AJAX. I need that data for other functions after verification is done. How can I keep that data handy? Should I use Tempdata on the server side?

You could store the data on Server side or the Client side. On the server side, you could use Session to store the records. On the Client side, you could use HTML Web Storage to store the data.

To use Session in asp.net core application, the Startup.cs must contain:

  • Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core.
  • A call to AddSession in ConfigureServices.
  • A call to UseSession in Configure.

Code as below:

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();
    });
}

Then, to use sessions to store the object type data, we should create a SessionExtensions.cs file and contain the following code:

//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);
    }
}

After that, refer the following code to store/get data from session:

        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);

The HTML web storage provides two objects for storing data on the client:

  • window.localStorage - stores data with no expiration date
  • window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

The use of the web storage as below:

    //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..
    }

Finally, you could refer the following sample code to store data in Asp.net Core using JQuery Ajax.

Models:

public class UserViewModel
{
    public string userkey { get; set; }
    public string Email { get; set; }
}

HomeController.cs (Add HttpPost attribute in the head of the ValidateUser method):

    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 });
    } 

View (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>

At the end of Index2.cshtml page, use the following script to submit data to controller:

@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>
}

The result as below (Open the F12 developer tools, then we could find the web storage in the Application panel):

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...