Save information with JSON format

I'm trying to utilize JSON for updating database records without triggering a postback, but I'm struggling with the implementation. This is my first time attempting this, so any guidance in the right direction would be greatly appreciated.

(Note: The irrelevant explanation – I have a list of sortable items with editable text using a jQuery plugin. When users click submit, I want their records to be updated. The functionality will resemble something like this.)

This specific JavaScript function creates an array of objects. However, I'm unsure about the next steps after generating the array. It gets invoked by the button's onClick event.

 function SaveLinks() {
     var list = document.getElementById('sortable1');
     var links = [];

     for (var i = 0; i < list.childNodes.length; i++) {
         var link = {};
         link.id = list.childNodes[i].childNodes[0].innerText;
         link.title = list.childNodes[i].childNodes[1].innerText;
         link.description = list.childNodes[i].childNodes[2].innerText;
         link.url = list.childNodes[i].childNodes[3].innerText;

         links.push(link);
     }

     //This is the part where I need help deciding what to do with my array.
 }

I aim to trigger an update method through this process to save the data into the database. Below is the code-behind function that the JavaScript will call.

    public void SaveList(object o )
    {
        //Need to cast and process the information
    }

All assistance is welcome!

Answer №1

I recently completed a similar task using MVC, and although the process may vary slightly, it is manageable.

While not necessary, I recommend creating contracts in both JS on the client side and C# on the server side to ensure interface consistency.

Below is a snippet of sample Javascript code (utilizing the jQuery library):

var item = new Item();
item.id = 1;
item.name = 2;
$.post("Item/Save", $.toJSON(item), function(data, testStatus) {
  /*User can be notified that the item was saved successfully*/
  window.location.reload();
}, "text");

In this example, the expected return content from the server is text, but it could also be XML, HTML, or additional JSON data.

The server-side code would resemble something like this:

public ActionResult Save()
{
    string json = Request.Form[0];

    var serializer = new DataContractJsonSerializer(typeof(JsonItem));
    var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
    JsonItem item = (JsonItem)serializer.ReadObject(memoryStream);
    memoryStream.Close();

    SaveItem(item);

    return Content("success");
}

I hope this explanation clarifies the process for you.

Answer №2

Instead of using CodeBehind, you should create a new action for this task.

The action you create will need to take an argument that can be created from the data posted by the user. In your case, the data is coming in as a JavaScript object, not JSON. Therefore, you'll need a type like the following:

public class Link
{
    public int? Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }
}

It's important to note the use of nullable int. If you have non-nullable types in your edit models and the user doesn't submit a value for that property, binding will fail. Using nullable types allows you to handle null values gracefully in your controller.

Next, you need to add an action:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoStuff(IEnumerable<Link> saveList)
{
    Repository.SaveLinks(saveList);
    return Json(true);
}

Modify your JS object so that it can be understood by MVC's DefaultModelBinder:

 var links = {};
 for (var i = 0; i < list.childNodes.length; i++) {
     links["id[" + i + "]"] = list.childNodes[i].childNodes[0].innerText;
     links["title[" + i + "]"] = list.childNodes[i].childNodes[1].innerText;
     links["description[" + i + "]"] = list.childNodes[i].childNodes[2].innerText;
     links["url[" + i + "]"] = list.childNodes[i].childNodes[3].innerText;
 }

Lastly, invoke the action in your JS code:

//In this part, you need to work with your array. Now you know how!
// Assuming jQuery is present -- handling with jQuery is much simpler
$.post("/path/to/DoStuff", links, function() { 
    // Operation successful!
    },
    'json');

Answer №3

Regrettably, JavaScript does not come equipped with a built-in function for transforming a structure into JSON format. Consequently, if you intend to send JSON data through an Ajax request, you will need to either manipulate the string manually or utilize a third-party serializer. (There are a couple of plugins available in jQuery that can assist with this task.)

Nevertheless, it is worth noting that sending JSON to the server via HTTP may not always be necessary for processing. You can opt for an Ajax POST request and encode the form using the standard method (

application/x-www-form-urlencoded
).

While this approach may not support transmitting structured data like nested arrays, you could potentially work around this limitation by assigning incremental names to the fields within your links structure. For instance, using naming conventions such as links.id_1, links.id_2, and so forth.

If you choose to follow this strategy, handling the process with something like jQuery becomes quite straightforward:

jQuery.post('/foo/yourapp', links, function() { alert('posted stuff'); });

Subsequently, you would need to reorganize the received data on the server side accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transformed the Next.js Pages Router into an Application Router

Looking to make a change in my API written with Nextjs's Pages Router. Currently, it serves as a proxy for downloads and I am interested in converting it to the App Router method. Does anyone have any guidance on how to go about implementing this? imp ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons: <button id="button1" onclick="isClicked(this.id)">B1</button> <button id="button2" onclick="isClicked(this.id) ...

Verify whether the image was uploaded from the camera or gallery within a mobile browser

Currently, I have the following code snippet: <input id="video-selector" type="file" name="files[]" accept="video/*,image/*" capture="camera" > I am looking for a way to determine whether an image was captured using the camera or selected from the ...

Error: The object referenced does not contain the 'bxSlider' method

I encountered an error in the console that reads: Uncaught TypeError: Object [object Object] has no method 'bxSlider' I am puzzled as to why this issue is occurring. Everything was functioning perfectly until I implemented it into a NetSuite st ...

Issue encountered while sending data to controller function

Here is the error message: The parameters dictionary has a null entry for parameter 'id' of non-nullable type 'System.Int32' in the method 'System.Web.Mvc.ActionResult Delete(Int32)' within 'Grid.Controller ...

What could be causing the observable collection to display the correct number of objects, yet have them all appear empty?

I am offering the following service @Injectable() export class LMSVideoResulful { getVideos( enrolmentId : number ) :Observable<Array<Video>> { var x = new Array<Video>(); //https://www.youtube.com/embed/MV0vLcY65 ...

Issue with jQuery click event not functioning on IE11 in Windows8

Having a strange issue where the click event is triggering a console.log but failing to execute the addClass function on the intended HTML element. It's working fine in Chrome on my Mac, but not on a Windows8 Surface. Any ideas on what could be causin ...

Moving a view outside of a scroll view in React Native: Tips and tricks

Currently, I am working on a unique feature where there is a horizontal ScrollView containing pink boxes. Each box is constructed using Animated.View along with a GestureDetector to handle the dragging functionality. My goal is to enable the user to drag a ...

Tips on incorporating Vue.js for creating a reusable modal template?

Currently, I've developed a web app that loads a dynamic dashboard using data from a SQL database. The dashboard elements have buttons that are supposed to trigger modals displaying problem information for user interaction. Lately, I've integrat ...

The React setState function isn't updating the state as expected when used within the useEffect hook

I'm new to using hooks and I'm facing an issue with setState when trying to update data received from an API. Despite logging the response data successfully, it seems that the state does not update as expected. My useEffect function is set to run ...

Leveraging String Interpolation for Retrieving Array Values in Angular2 Application

In my Angular2 application, I have implemented a functionality where I loop through a list of users and display an icon to represent each user. Now, I want to enhance the user experience by using material2's tooltip (mdTooltip) feature to display the ...

Issue with disabled button in Angular 2 when using Chrome's autocomplete feature

In a basic login form, the login button is initially disabled with the following code: [disabled]="!password || !loginName" When Chrome's autocomplete feature fills in the values for loginName and password, the button remains disabled after the pa ...

Encountering an Unforeseen Syntax Error: Unexpected Token ':'

I cannot understand why this issue keeps occurring when making an API request. Even though the data I requested appears correctly in the network tab, it does not print out in the console. The API I am using is Musixmatch API. Any suggestions? ...

What is the best way to extract data from JSON objects in Java, considering their unique keys and values?

I have expertise in parsing JSON data like the following: { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" }, { "id": "1003", "type": "Blueberry" }, { "id": "1004", "type": "Devil's Food" } With this type of data, ...

Ways to loop through the outcome of an array within the Document Object Model (DOM)

https://i.sstatic.net/Cmfx0.jpg Hey there, I'm currently facing an issue while trying to loop through an array to access the class of tag.highlight within a span that only becomes active after being iterated over 30 times with span.tag. My main goal ...

How can LoadMore pagination be implemented for a grouped ListView in Windows Phone 8.1?

Could anyone suggest a method other than using ListViewBase.LoadMoreItemsAsync for implementing pagination in a grouped ListView (CollectionViewSource)? Any insights or alternatives would be greatly appreciated. ...

Can the Three.js WebGLRenderer be utilized on a node.js server environment?

There seems to be conflicting opinions on whether running WebGLRenderer on the server is feasible. Some say it can't be done, while others claim they are making efforts to achieve it but haven't succeeded yet. Is there a way to accomplish this? ...

When utilizing Blazor to create dynamic URLs within a loop, incorrect references may be generated

While working on a Blazor web assembly application, I encountered an issue when trying to loop over content to generate URLs for MP3 files. The media files are named "1.mp3", "2.mp3", "3.mp3", and so on. Imagine having a razor page with the following con ...

Can anyone suggest a simpler method for removing all fixed sizes assigned to HTML nodes without having to write code for it?

When working with input strings, I often encounter complex HTML code generated by an RTF to HTML conversion tool. The issue lies in the fixed sizes set for tables, making them inflexible and non-dynamic. To address this problem, I have attempted to create ...