In this post, I would like to talk about a common problem that most developers encounter when they want to send JSON array via Ajax POST to the controller action.
Note: Code explanations are done using C#, ASP.NET MVC 4 and jQuery.
My scenario is simple.I have an object called ShortcutModel in the Model. It looks as follows.
An array of Shortcuts are stored in the database as a JSON string like follows.
So when the user does some changes to the Shortcuts in his profile (adding or removing) and want to save the data back to the database.
Right now, what the developer should do is,
Let me provide some .cshtml code snippet so that it is easy to understand the jQuery code.
Please note that the complete view is skipped for simplicity.
First, do an Ajax POST and send array of collected Shortcut objects as a JSON string to the controller.
The jQuery POST
As you can see, here we pass only a single parameter which is jsonShortcut but you can pass multiple parameters to the controller action separated with a comma. The JSON.stringify method converts a value to JSON.
Second, Let's write the controller action.
Hope this will be useful during the battle between jQuery and controller actions.
Note: Code explanations are done using C#, ASP.NET MVC 4 and jQuery.
My scenario is simple.I have an object called ShortcutModel in the Model. It looks as follows.
An array of Shortcuts are stored in the database as a JSON string like follows.
So when the user does some changes to the Shortcuts in his profile (adding or removing) and want to save the data back to the database.
Right now, what the developer should do is,
- Do call an Ajax POST and send the data to the controller
- Execute the controller action.
Let me provide some .cshtml code snippet so that it is easy to understand the jQuery code.
Please note that the complete view is skipped for simplicity.
First, do an Ajax POST and send array of collected Shortcut objects as a JSON string to the controller.
The jQuery POST
As you can see, here we pass only a single parameter which is jsonShortcut but you can pass multiple parameters to the controller action separated with a comma. The JSON.stringify method converts a value to JSON.
Second, Let's write the controller action.
Hope this will be useful during the battle between jQuery and controller actions.
No comments:
Post a Comment