How to use serialized data in asp.net mvc and c #

I am using jQuery UI sortable to sort the list in the DOM. I successfully execute the ajax function that creates this line for my mvc action:

list[]=2&list[]=3&list[]=28&list[]=1 

I'm trying to figure out how to get this serialized list of numbers in a List<int> so that I can actually access them from C #.

How can I do it? I have already tried this method:

  [HttpPost] public string RoleTierUpdate( string[] form) { StringBuilder sb = new StringBuilder(); foreach (var item in form) { sb.AppendFormat("id: {0}<br />", item); } return sb.ToString(); } 

I thought I could convert a string array to a list of integers. But this led to the following conclusion:

  id: 2 id: , id: 3 id: , id: 2 id: 8 id: , id: 1 

Is there an easier way to get this data into an int list?

Edit

Here is the code that executes the ajax post:

 <script type="text/javascript"> // Sortable $(document).ready(function () { $("#sortThis").sortable({ handle: '.handle', update: function () { // get new order var order = $('#sortThis').sortable('serialize'); // excecute ajax for db update $.post( "/find/AdminMember/RoleTierUpdate/", order, function (data) { $("#info").html(data); } ); $("#info2").html(">>" + order + "<<"); } }); }); </script> 

order contains the line shown above.

Edit 2

Controller updated to:

  [HttpPost] public string RoleTierUpdate( List<int> list, MemberData md) // change to List<int> list { StringBuilder sb = new StringBuilder(); if (list != null) // added check for null { foreach (var item in list) { sb.AppendFormat("id: {0}<br />", item); } } else { sb.Append("form is null"); } return sb.ToString(); } 

Updated ajax to:

  $(document).ready(function () { jQuery.ajaxSettings.traditional = true; // added $("#sortThis").sortable({ handle: '.handle', update: function () { // get new order var order = $('#sortThis').sortable('serialize'); // excecute ajax for db update $.post( "/find/AdminMember/RoleTierUpdate/", order, function (data) { $("#info").html(data); } ); $("#info2").html(">>" + order + "<<"); } }); }); 

The way out of this:

 form is null 
+4
source share
2 answers

It seems like the reason MVC modelbinder didn't want to bind the string

 list[]=2&list[]=3&list[]=28&list[]=1 

until List<int> list is due to "[]" in keys. I added this javascript to my jQuery:

 // get new order var order = $('#sortThis').sortable('serialize'); order = order.replace(/\[\]/gi, "") 

As soon as I pulled "[]" from the keys, everything was great. The action returned this result:

 id: 2 id: 3 id: 28 id: 1 

This is exactly what I need. Model binding to List<int> works fine.

+2
source

ASP.NET will automatically detect that you are trying to use a list. Do it:

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult RoleTierUpdate(List<String> list) 

or replace String with Int32 if you expect integers.

0
source

Source: https://habr.com/ru/post/1332436/


All Articles