如何在Asp.net MVC C#中从会话而不是数据库中插入和获取数据

时间:2018-10-22 10:12:31

标签: c# session asp.net-mvc-5

现在,我已经了解了应用CRUD操作(无论是否具有页面刷新)。但是现在我想要的是从会话而不是数据库中保存和检索数据。从前两天开始,我就一直在搜索此问题,但是我没有找到任何可信赖的资源来解决或详细解释如何完成此工作?

我知道,在在线购物或在线测验系统的情况下,最好使用会话来存储临时数据,而不是将其保存到数据库中,因为这会浪费大量资源。

如果有人解析或分享一些可靠的教程链接来跟随它,我将是这项技术的初学者,在此先感谢。

1 个答案:

答案 0 :(得分:1)

您可以像这样在控制器中声明全局会话变量和全局GUID数据类型变量(用于生成唯一ID作为主键)。

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;

然后您可以在post方法中使用它们,以便将数据插入会话

  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在这里用于返回对ajax调用的响应,这取决于人是否要在表末尾添加数据,您可以使用此行代码。如果要在页面刷新上追加,只需添加return Json(“ Ok”)。

这是我的Javascript文件,该文件用于通过ajax调用读取数据并将数据发布到控制器方法,这有助于我们避免页面刷新。

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



};

});

这有望将您的数据插入会话中。

要以表格列表的形式查看插入的数据,可以使用如下所示的get方法:

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

    }

这是用于将数据插入到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>}

如上所述,您已经完成了所有CRUD操作,此答案只是关于如何从会话中插入和获取数据的想法。通过遵循与该策略相同的策略,将帮助您完成CRUD中剩余的所有操作。希望这篇文章对您有所帮助。