简体   繁体   中英

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. I need to store the data in SQL Server. But I don't want to create that many columns in the SQL Server table. 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 .

[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. 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. 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):

在此处输入图片说明

Javascript Code:

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): 在此处输入图片说明

Error in Chrome Developer Console:

This error is at JSON.parse(json);

在此处输入图片说明

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

Update:

After fixing the javascript code, it works:

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.

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

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

        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM