0

Right now I have understanding of applying CRUD operations with or without page refresh. But now what I want is to save and retrieve data from sessions instead of database. I have been searching to this matter from previous two days but I haven't found any credible resource to follow which can resolve or give explanation in detail how this can be done ?.

I know that in the scenario of online shopping or online quiz systems ,It is highly preferably to use sessions to store temporary data instead of saving it to database which becomes costly due to high consumption of resources.

I am Beginner to this technology if someone resolve or share some credible links of tutorials to follow it would be really appreciable, Thanks in advance.

Ibrahim Inam
  • 141
  • 10

1 Answers1

1

You can declare a global session variable and a global GUID datatype variable(for generation of unique Id as a primary Key) in your controller like this.

public List<Models.Details> SessionList
    {
        get
        {
            var obj = Session["myList"];
            if (obj == null) { obj = Session["myList"] = new List<Models.Details>(); }
            return (List<Models.Details>)obj;
        }
        set
        {
            Session["myList"] = value;
        }
    }
    public Guid guid;

then You can use them in your post method for insertion of data into session like this

  public ActionResult Test(Models.Details[] itemlist)
    {



        foreach (Models.Details d in itemlist)
        {
            guid = Guid.NewGuid();
            d.IdString = guid;
            SessionList.Add(d);


        }

        return Json(new { success = true, id = itemlist[0].IdString, name = itemlist[0].Name, city = itemlist[0].City, country = itemlist[0].Country });

    }

return json is used here to give back a response to ajax call, It depends on person if you want to append data at the end of the table you can use this line of code. If you want to append on page refresh simply add return Json("Ok").

Here is my Javascript File which is used to read and post data to controller method with an ajax call which helps us to avoid a page refresh.

$(document).ready(function(){
$("#buttonid").on("click", Submit); 
function Submit() {

    var itemlist = [];

    //get cell values, instead of the header text.#tablePost > tbody > t
    $("#tblData > tbody > tr").each(function () {
        debugger;
        var name = $(this).find("[name='Name[]']").val();
        var city = $(this).find("[name='City[]']").val();
        var country = $(this).find("[name='Country[]']").val();
        var tdlist = $(this).find("td");
        var Details = { Name: name, City: city, Country: country };
        itemlist.push(Details);
    })

    console.log(itemlist)
    $.ajax({
        url: '/Student/Test',
        dataType: "json",
        data: JSON.stringify({ itemlist: itemlist }),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            if (response.success) {
                $("#tblDetails").append(
                    "<tr data-record-id=" + response.id + ">" +
                    "<td>" + response.name + "</td>" +
                    "<td>" + response.city + "</td>" +
                    "<td>" + response.country + "</td>" +
                    "<td> <a class='edit-record' data-model-id=" + response.id + " onclick='EditGet(this)'><img src='/UserImages/edit.png'/></a><a class='delete' data-model-id=" + response.id + " onclick='DeleteGet(this)'><img src='/UserImages/delete.png'/></a></td>" +
                    "</tr>"
                );
            }
        },
        error: function () {
            alert("error");
        }
        });



};

});

This will hopefully insert your data in session.

To view inserted data in form of tabled list you can use your get method like this as it is done below:

 public ActionResult Test()

    {
        List<Models.Details> detaillist = new List<Models.Details>();

            var data = SessionList;
            var query = data.Select(x => new Models.Details
            {
                IdString = x.IdString,
                Name = x.Name,
                City = x.City,
                Country = x.Country
            });
            detaillist = query.ToList();

                return View(detaillist);

    }

Here it is razor view for insertion of data into View Table :

@model List<Inventory.Models.Details>
<button id="btnSubmit">Submit Data</button>
@using (Html.BeginForm("Test", "Student", FormMethod.Post))
{
<table id="tblData" class=" table-responsive table-bordered table-striped table-condensed">
    <thead>
        <tr>
            <th>Name</th>
            <th>City</th>
            <th>Country</th>
            <th>Options</th>
        </tr>
    </thead>
    <tbody></tbody>

</table>

<input type="button" value="submit" id="btnInsert" />

<table id="tblDetails" class=" table-responsive table-bordered table-striped table-condensed">
    <thead>
        <tr>
            <th>Name</th>
            <th>City</th>
            <th>Country</th>
            <th>Options</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr data-record-id="@item.Id">
                <td>@item.Name</td>
                <td>@item.City</td>
                <td>@item.Country</td>
                <td>
                    <a class="edit-record" data-model-id="@item.Id" onclick="EditGet(this)" href="javascript:;">
                        <img id="image" src="/UserImages/edit.png" />
                    </a>
                    <a class="deleteimage" onclick="DeleteGet(this)" data-model-id="@item.Id">
                        <img src="/UserImages/delete.png" />
                    </a>
                </td>

            </tr>
        }
    </tbody>

</table>}

As you have mentioned above that you have done all CRUD operations, This answer is just an Idea of how data is inserted and fetched from a session. By following the same strategy as this one will help you out to complete all of the remaining operation you have in CRUD. I hope this post will help you out.

Ibrahim Inam
  • 141
  • 10