Ad

Serializing A List In C# And Deserializing It Into Js Array

- 1 answer

I have a razor part in my javascript but can't access the js-variable that has been put in as a parameter to the js-function.

I am trying to serialize a List and then deserialize the json string into a js-array.

<script>
function listContainerBlobs(json, container) {
    @*var arr = @JsonConvert.DeserializeObject(json);*@
    var arr = JSON.parse(json);
    var blobs = document.getElementById('container-blob-display').innerHTML = "<h4>" + container + "</h4>";
    var otherDiv = document.getElementById('section-1');
    var thisDiv = document.getElementById('section-2');

    otherDiv.style.display = 'none';
    thisDiv.style.display = 'block';

    var blobNumber = 0;

    for (i = 0; i < arr.length; i++){
        blobNumber++;
        var blobId = "blobId" + blobNumber;
        blobs += "<p class='search-result' id='" + blobId + "' onclick='downloadBlob('" + blobId + "', '" + arr[i].Name + "', '" + container + "')' style='float: left; '>" + arr[i].Name + "</p>";
    }
}</script>

This is the C# code in the razor page which serializes the List returned by a method. I am wondering if the formats of the json strings are different and therefore I cannot deserialize the json string within js.

var blobs = await Model.ListContainerBlobs(container.Name);
var jsonBlob = Json.Serialize(blobs);
//var jsonBlob = JsonConvert.SerializeObject(blobs);

I use blobs in a few lopps and stuff in the html-page but thought I'd reuse this methodcall for the parameter in the js-function listContainerBlobs(json, container) therefore the json serialization.

Js-function call:

<p class="search-result blob-container" id="@containerId" onclick="listContainerBlobs('@jsonBlob','@containerModel.Name')">@containerModel.Name</p>

Error received when debugging in the browser: enter image description here

By reading this, this and this I guess I have to just accept that I can't call a js-variable inside razor.

Does anyone have a workaround on this or maybe a better solution to the serializing/deserializing of this c# list?

If important here are the different json types I serialize into

  • Json.Serialize(blobs); :

"[{\"StreamWriteSizeInBytes\":4194304,\"ServiceClient\":{\"BufferManager\":null,\"Credentials\":{\"SASToken\":null,\"AccountName\":\"devstoreaccount1\",\"KeyName\":null,\"IsAnonymous\":false,\"IsSAS\":false,\"IsSharedKey\":true,\"IsToken\":false,\"SASSignature\":null},\"BaseUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary\"},\"DefaultRequestOptions\":{\"RetryPolicy\":{},\"AbsorbConditionalErrorsOnRetry\":null,\"LocationMode\":0,\"ServerTimeout\":null,\"MaximumExecutionTime\":null,\"ParallelOperationThreadCount\":1,\"SingleBlobUploadThresholdInBytes\":134217728,\"UseTransactionalMD5\":null,\"StoreBlobContentMD5\":null,\"DisableContentMD5Validation\":null},\"RetryPolicy\":{},\"DefaultDelimiter\":\"/\",\"AuthenticationScheme\":1},\"StreamMinimumReadSizeInBytes\":4194304,\"Properties\":{\"CacheControl\":null,\"ContentDisposition\":null,\"ContentEncoding\":null,\"ContentLanguage\":null,\"Length\":68,\"ContentMD5\":\"YUP3oQ5rwX9qEtwa7Op0Iw==\",\"ContentType\":\"text/plain\",\"ETag\":\"\\"0x8D757BD9E066830\\"\",\"Created\":\"2019-10-22T09:06:29+00:00\",\"LastModified\":\"2019-10-23T13:33:40+00:00\",\"BlobType\":2,\"LeaseStatus\":2,\"LeaseState\":1,\"LeaseDuration\":0,\"PageBlobSequenceNumber\":null,\"AppendBlobCommittedBlockCount\":null,\"IsServerEncrypted\":true,\"IsIncrementalCopy\":false,\"StandardBlobTier\":0,\"RehydrationStatus\":null,\"PremiumPageBlobTier\":null,\"BlobTierInferred\":false,\"BlobTierLastModifiedTime\":null,\"DeletedTime\":null,\"RemainingDaysBeforePermanentDelete\":null},\"Metadata\":{},\"Uri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container/FirstBlob.txt\"},\"SnapshotTime\":null,\"IsSnapshot\":false,\"IsDeleted\":false,\"SnapshotQualifiedUri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt\",\"SnapshotQualifiedStorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container/FirstBlob.txt\"},\"CopyState\":null,\"Name\":\"FirstBlob.txt\",\"Container\":{\"ServiceClient\":{\"BufferManager\":null,\"Credentials\":{\"SASToken\":null,\"AccountName\":\"devstoreaccount1\",\"KeyName\":null,\"IsAnonymous\":false,\"IsSAS\":false,\"IsSharedKey\":true,\"IsToken\":false,\"SASSignature\":null},\"BaseUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary\"},\"DefaultRequestOptions\":{\"RetryPolicy\":{},\"AbsorbConditionalErrorsOnRetry\":null,\"LocationMode\":0,\"ServerTimeout\":null,\"MaximumExecutionTime\":null,\"ParallelOperationThreadCount\":1,\"SingleBlobUploadThresholdInBytes\":134217728,\"UseTransactionalMD5\":null,\"StoreBlobContentMD5\":null,\"DisableContentMD5Validation\":null},\"RetryPolicy\":{},\"DefaultDelimiter\":\"/\",\"AuthenticationScheme\":1},\"Uri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container\"},\"Name\":\"first-container\",\"Metadata\":{},\"Properties\":{\"ETag\":null,\"HasImmutabilityPolicy\":null,\"HasLegalHold\":null,\"LastModified\":null,\"LeaseStatus\":0,\"LeaseState\":0,\"LeaseDuration\":0,\"PublicAccess\":null}},\"Parent\":{\"ServiceClient\":{\"BufferManager\":null,\"Credentials\":{\"SASToken\":null,\"AccountName\":\"devstoreaccount1\",\"KeyName\":null,\"IsAnonymous\":false,\"IsSAS\":false,\"IsSharedKey\":true,\"IsToken\":false,\"SASSignature\":null},\"BaseUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary\"},\"DefaultRequestOptions\":{\"RetryPolicy\":{},\"AbsorbConditionalErrorsOnRetry\":null,\"LocationMode\":0,\"ServerTimeout\":null,\"MaximumExecutionTime\":null,\"ParallelOperationThreadCount\":1,\"SingleBlobUploadThresholdInBytes\":134217728,\"UseTransactionalMD5\":null,\"StoreBlobContentMD5\":null,\"DisableContentMD5Validation\":null},\"RetryPolicy\":{},\"DefaultDelimiter\":\"/\",\"AuthenticationScheme\":1},\"Uri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container\"},\"Container\":{\"ServiceClient\":{\"BufferManager\":null,\"Credentials\":{\"SASToken\":null,\"AccountName\":\"devstoreaccount1\",\"KeyName\":null,\"IsAnonymous\":false,\"IsSAS\":false,\"IsSharedKey\":true,\"IsToken\":false,\"SASSignature\":null},\"BaseUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary\"},\"DefaultRequestOptions\":{\"RetryPolicy\":{},\"AbsorbConditionalErrorsOnRetry\":null,\"LocationMode\":0,\"ServerTimeout\":null,\"MaximumExecutionTime\":null,\"ParallelOperationThreadCount\":1,\"SingleBlobUploadThresholdInBytes\":134217728,\"UseTransactionalMD5\":null,\"StoreBlobContentMD5\":null,\"DisableContentMD5Validation\":null},\"RetryPolicy\":{},\"DefaultDelimiter\":\"/\",\"AuthenticationScheme\":1},\"Uri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container\",\"StorageUri\":{\"PrimaryUri\":\"http://127.0.0.1:10000/devstoreaccount1/first-container\",\"SecondaryUri\":\"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container\"},\"Name\":\"first-container\",\"Metadata\":{},\"Properties\":{\"ETag\":null,\"HasImmutabilityPolicy\":null,\"HasLegalHold\":null,\"LastModified\":null,\"LeaseStatus\":0,\"LeaseState\":0,\"LeaseDuration\":0,\"PublicAccess\":null}},\"Parent\":null,\"Prefix\":\"\"},\"BlobType\":2}]"

  • Jsonconvert.SerializeObject(blobs); :

{[{"streamWriteSizeInBytes":4194304,"serviceClient":{"bufferManager":null,"credentials":{"sasToken":null,"accountName":"devstoreaccount1","keyName":null,"isAnonymous":false,"isSAS":false,"isSharedKey":true,"isToken":false,"sasSignature":null},"baseUri":"http://127.0.0.1:10000/devstoreaccount1","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary"},"defaultRequestOptions":{"retryPolicy":{},"absorbConditionalErrorsOnRetry":null,"locationMode":0,"serverTimeout":null,"maximumExecutionTime":null,"parallelOperationThreadCount":1,"singleBlobUploadThresholdInBytes":134217728,"useTransactionalMD5":null,"storeBlobContentMD5":null,"disableContentMD5Validation":null},"retryPolicy":{},"defaultDelimiter":"/","authenticationScheme":1},"streamMinimumReadSizeInBytes":4194304,"properties":{"cacheControl":null,"contentDisposition":null,"contentEncoding":null,"contentLanguage":null,"length":68,"contentMD5":"YUP3oQ5rwX9qEtwa7Op0Iw==","contentType":"text/plain","eTag":"\u00220x8D757BD9E066830\u0022","created":"2019-10-22T09:06:29+00:00","lastModified":"2019-10-23T13:33:40+00:00","blobType":2,"leaseStatus":2,"leaseState":1,"leaseDuration":0,"pageBlobSequenceNumber":null,"appendBlobCommittedBlockCount":null,"isServerEncrypted":true,"isIncrementalCopy":false,"standardBlobTier":0,"rehydrationStatus":null,"premiumPageBlobTier":null,"blobTierInferred":false,"blobTierLastModifiedTime":null,"deletedTime":null,"remainingDaysBeforePermanentDelete":null},"metadata":{},"uri":"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container/FirstBlob.txt"},"snapshotTime":null,"isSnapshot":false,"isDeleted":false,"snapshotQualifiedUri":"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt","snapshotQualifiedStorageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1/first-container/FirstBlob.txt","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container/FirstBlob.txt"},"copyState":null,"name":"FirstBlob.txt","container":{"serviceClient":{"bufferManager":null,"credentials":{"sasToken":null,"accountName":"devstoreaccount1","keyName":null,"isAnonymous":false,"isSAS":false,"isSharedKey":true,"isToken":false,"sasSignature":null},"baseUri":"http://127.0.0.1:10000/devstoreaccount1","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary"},"defaultRequestOptions":{"retryPolicy":{},"absorbConditionalErrorsOnRetry":null,"locationMode":0,"serverTimeout":null,"maximumExecutionTime":null,"parallelOperationThreadCount":1,"singleBlobUploadThresholdInBytes":134217728,"useTransactionalMD5":null,"storeBlobContentMD5":null,"disableContentMD5Validation":null},"retryPolicy":{},"defaultDelimiter":"/","authenticationScheme":1},"uri":"http://127.0.0.1:10000/devstoreaccount1/first-container","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1/first-container","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container"},"name":"first-container","metadata":{},"properties":{"eTag":null,"hasImmutabilityPolicy":null,"hasLegalHold":null,"lastModified":null,"leaseStatus":0,"leaseState":0,"leaseDuration":0,"publicAccess":null}},"parent":{"serviceClient":{"bufferManager":null,"credentials":{"sasToken":null,"accountName":"devstoreaccount1","keyName":null,"isAnonymous":false,"isSAS":false,"isSharedKey":true,"isToken":false,"sasSignature":null},"baseUri":"http://127.0.0.1:10000/devstoreaccount1","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary"},"defaultRequestOptions":{"retryPolicy":{},"absorbConditionalErrorsOnRetry":null,"locationMode":0,"serverTimeout":null,"maximumExecutionTime":null,"parallelOperationThreadCount":1,"singleBlobUploadThresholdInBytes":134217728,"useTransactionalMD5":null,"storeBlobContentMD5":null,"disableContentMD5Validation":null},"retryPolicy":{},"defaultDelimiter":"/","authenticationScheme":1},"uri":"http://127.0.0.1:10000/devstoreaccount1/first-container","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1/first-container","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container"},"container":{"serviceClient":{"bufferManager":null,"credentials":{"sasToken":null,"accountName":"devstoreaccount1","keyName":null,"isAnonymous":false,"isSAS":false,"isSharedKey":true,"isToken":false,"sasSignature":null},"baseUri":"http://127.0.0.1:10000/devstoreaccount1","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary"},"defaultRequestOptions":{"retryPolicy":{},"absorbConditionalErrorsOnRetry":null,"locationMode":0,"serverTimeout":null,"maximumExecutionTime":null,"parallelOperationThreadCount":1,"singleBlobUploadThresholdInBytes":134217728,"useTransactionalMD5":null,"storeBlobContentMD5":null,"disableContentMD5Validation":null},"retryPolicy":{},"defaultDelimiter":"/","authenticationScheme":1},"uri":"http://127.0.0.1:10000/devstoreaccount1/first-container","storageUri":{"primaryUri":"http://127.0.0.1:10000/devstoreaccount1/first-container","secondaryUri":"http://127.0.0.1:10000/devstoreaccount1-secondary/first-container"},"name":"first-container","metadata":{},"properties":{"eTag":null,"hasImmutabilityPolicy":null,"hasLegalHold":null,"lastModified":null,"leaseStatus":0,"leaseState":0,"leaseDuration":0,"publicAccess":null}},"parent":null,"prefix":""},"blobType":2}]}

To recreate this, serialize a List by C#, send the json string through onclick="" to your js-function and deserialize the string inside the function.

Ad

Answer

I had to do a workaround by creating a object of my own containing the values that I wanted/needed.

List<object> objects = new List<object>();

objects.Add(new
    {
        blobCount = blobs.Count,
        blobs = blobs.Select(x => new
        {
            Name = x.Name,
            Container = x.Container,
            Blobtype = x.BlobType,
            Uri = x.Uri
         })
     });

var jsonBlob = JsonConvert.SerializeObject(blobObject);

I noticed that the result of deserializing the json-string was faulty. One part of the string wasn't deserialized correctly (according to my human eyes and mind but probably correctly according to the json format). I didn't need this property anyway so this works perfectly in my case.

Hopefully this might help someone else...

Also according to this link (which checks if the format of your json-string is valid) the Json.Serialize(i) was correct but became faulty inside the browser, and the JsonConverter.SerializeObject(i) was invalid. Though after making a new list of objects the later was the one which was wokring and not the first one.

Ad
source: stackoverflow.com
Ad