简体   繁体   English

ASP.Net Core - 在 SQL Server 数据库中存储和检索 FormCollection

[英]ASP.Net Core - Store and Retrieve FormCollection in SQL Server database

I have a razor form that collects a long list of inputs from the user.我有一个 razor 表单,可以从用户那里收集一长串输入。 I need to store the data in SQL Server.我需要将数据存储在 SQL Server 中。 But I don't want to create that many columns in the SQL Server table.但我不想在 SQL Server 表中创建那么多列。 So my idea was to have a column FormData of type nvarchar(max) , convert the FormCollection object to Json and store it in table.FormData .所以我的想法是有一个nvarchar(max)类型的FormData列,将FormCollection对象转换为 Json 并将其存储在table.FormData

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
    try
    {
        string json = JsonConvert.SerializeObject(collection);

        MyObject form = new MyObject()
        {
            id = 1,
            formdata = json
        };

        repository.Add(form);

        return RedirectToAction(nameof(Index));
    }
    catch
    {
        return View();
    }
}

Storing the data works fine, but when I retrieve it, the deserialization fails.存储数据工作正常,但是当我检索它时,反序列化失败。

I wrote an API to retrieve it.我写了一个 API 来检索它。 The return data has escape characters, and I believe that's what is causing the issue.返回数据有转义字符,我相信这就是导致问题的原因。

FormData:表格数据:

[
  {
    "id": 1,
    "formdata": "[{\"Key\":\"Name\",\"Value\":[\"Person1\"]},{\"Key\":\"EmpID\",\"Value\":[\"12345\"]},{\"Key\":\"inputDepartment\",\"Value\":[\"\"]},{\"Key\":\"inputLocation\",\"Value\":[\"\"]},{\"Key\":\"inputSupervisor\",\"Value\":[\"\"]},{\"Key\":\"inputExitDate\",\"Value\":[\"\"]},{\"Key\":\"optShouldEmailBeActive\",\"Value\":[\"on\"]},{\"Key\":\"optWhoHasAccess\",\"Value\":[\"on\"]},{\"Key\":\"__RequestVerificationToken\",\"Value\":[\"CfDJ8M9krkWO1eBMp3rh5qzs-Rv1bj07MLUgOrWTcXV-ivrIiXkHW30I0e0NYWuBtbvyjONlULoENzivw1NXfITYL1Y8CVIOoDgFW_ACPu9XLhHe8x5KUcOZ-FuLeXyR-Vj0Q7RE_lSmnDchZsB6ihVyW4bnFcKAjo9X62rknPNUHvvEjsIN7-1EHtrgMT2-TgLPkQ\"]}]",
  }
]

I couldn't find a way to avoid having those escape characters when serializing.我找不到在序列化时避免使用这些转义字符的方法。 I thought of using .replace() to remove these escape characters before storing, but I'm not sure if it's a good idea.我想过在存储之前使用.replace()删除这些转义字符,但我不确定这是否是个好主意。 I may end up doing that if I can't find a better solution.如果我找不到更好的解决方案,我可能最终会这样做。

============================ ============================

Deserialization Code:反序列化代码:

Just for testing I tried deserializing right after serializing, and it fails.只是为了测试,我在序列化后立即尝试反序列化,但失败了。

在此处输入图片说明

Ajax Call Result of JSON.stringify(data): JSON.stringify(data) 的 Ajax 调用结果:

在此处输入图片说明

Javascript Code: Javascript代码:

Tried removing escape characters.尝试删除转义字符。

function getData() {
    var url = baseURL + "api/itexit";

    $.ajax({
        url: url,
        type: "GET",
        success: function (data) {
            var json = JSON.stringify(data);
            json = json.replace(/\\"/g, '"');

            alert(json);
            var obj = JSON.parse(json);

            var a = "";
            $.each(obj, function (index) {
                a += obj[index].Key + "\n";
            });
            alert(a);
        },
        error: function (data) {

        }
    });
}

After removing escape characters, alert(json):删除转义字符后,alert(json): 在此处输入图片说明

Error in Chrome Developer Console: Chrome 开发者控制台中的错误:

This error is at JSON.parse(json);此错误位于 JSON.parse(json);

在此处输入图片说明

============================================= ==============================================

Update:更新:

After fixing the javascript code, it works:修复javascript代码后,它可以工作:

function getData() {
    var url = baseURL + "api/itexit";

    $.ajax({
        url: url,
        type: "GET",
        success: function (data) {
            var json = JSON.stringify(data);
            json = json.replace(/\\"/g, '"');
            json = json.replace('\"[', '[');
            json = json.replace(']\"', ']');

            var obj = JSON.parse(json);
            obj = obj[0].formdata;

            $.each(obj, function (index) {
                var o = obj[index];
                $("#" + o.Key).val(o.Value);
            });
        },
        error: function (data) {

        }
    });
}

Removed the escape characters, it fixed the issue.删除了转义字符,它解决了这个问题。

These lines did the trick in the following javascript getData() method.这些行在以下 javascript getData() 方法中起到了作用。

var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');

Javascript: Javascript:

function getData() {
    var url = baseURL + "api/itexit";

    $.ajax({
        url: url,
        type: "GET",
        success: function (data) {
            var json = JSON.stringify(data);
            json = json.replace(/\\"/g, '"');
            json = json.replace('\"[', '[');
            json = json.replace(']\"', ']');

            var obj = JSON.parse(json);
            obj = obj[0].formdata;

            $.each(obj, function (index) {
                var o = obj[index];
                $("#" + o.Key).val(o.Value);
            });
        },
        error: function (data) {

        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将列表从ASP.NET Core存储到SQL服务器? - How to store list in SQL Server from ASP.NET Core? 使用 Asp.Net Core 连接到本地 SQL 服务器数据库时遇到问题 - Trouble connecting to local SQL server database with Asp.Net Core ASP.NET 核心如何上传图片到SQL服务器数据库? - ASP.NET Core how to upload image to SQL Server database? 控制器中带有 FormCollection 模型的 ASP.NET CORE MVC 发布表单 - ASP.NET CORE MVC post form with FormCollection Model in controller 将 ASP.NET 内核连接到 SQL 服务器 - Connecting ASP.NET Core to SQL server 如何在ASP.net C#中将HTML文本编辑器内容存储和检索到SQL Server DB - how to store and retrieve the HTML text Editor contents to SQL Server DB in ASP.net C# 如何检索SQL Server表的列值并将其存储在label.C#ASP.Net中的文本 - How to retrieve column value of sql server table and store it in label.Text of c# ASP.Net 如何使用MS SQL Server数据库发布和部署Asp.net核心数据库优先应用程序 - How to publish and deploy an Asp.net Core Database first application with MS SQL Server Database 在服务器(Asp.Net Core)中生成PDF,并在浏览器(Angular)中检索 - Generate PDF in server (Asp.Net Core) and retrieve in Browser (Angular) ASP.NET和SQL Server数据库 - ASP.NET and SQL Server database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM