Pass a list from the client side to the server side in MVC C #
source link: https://www.codesd.com/item/pass-a-list-from-the-client-side-to-the-server-side-in-mvc-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Pass a list from the client side to the server side in MVC C #
Below is the code I'm using.
UpdateMultipulGroupContactId = "1,2,3,4";
Client Side function
function UpdateMultipulGroup() {
jQuery.ajax({
url: "/Json/Contact_Update_Groups_NickName",
type: "POST",
data: {
rid: UpdateMultipulGroupContactId,
gids: strArray,
nickname: 'abc'
},
dataType: "html",
success: function (data) {
var data = JSON.parse(data);
alert(data.message);
$("#Notes" + EditContactIdNotes).html($("#txtNotes").val());
CloseLightBox();
},
error: function (error) {
alert(error);
}
});
}
Server Side Function
public ActionResult Contact_Update_Groups_NickName(long rid, List<long> gids, string nickname)
I tried using arrays but I'm getting null values all the time.
How can I pass the UpdateMultipulGroupContactId
as a list from this function?
Binding to IList<T>
This blog post of mine can help substantionally because it basically talks about this very problem. How to bind client data to an IList<T>
in the controller action.
Blog post explains that values actually have to indexed as in
gids[0] = 1;
gids[1] = 2;
Sending complex JSON objects
But I've also written a very simple jQuery plugin that does all the conversion from a complex JSON object to an object that will easily be consumed by the MVC model binder. It is also able to consume various data types (dates etc) and convert them correctly for the Asp.net MVC to work out of the box without any changes on the server side.
By complex objects I mean JSON object with more than one level of hierarchy depth. Because the more complex the JSON object the more manipulation you have to do in your code. Plugin simplifies that to a single function call and providing it your JSON object.
Using the plugin would change your code to:
var data = {
rid: 1234567890, // this is a "long" number
gids: [1,2,3,4], // or "1,2,3,4".split(",")
nickname: 'abc'
};
function UpdateMultipulGroup() {
jQuery.ajax({
url: "/Json/Contact_Update_Groups_NickName",
type: "POST",
data: $.toDictionary(data),
success: ...
...
});
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK