Home > other >  Post select2 multiple values using form-data to controller
Post select2 multiple values using form-data to controller

Time:04-07

How to post select2 multiple values using form-data?

because form-data returns like below:

pid=0&members=staff1&members=staff2&members=staff7

members value would be a very dynamic value since it's multiple select, how to deal with this? I have tried to breakdown the select2 result and JSON.stringify first then pass it to the controller, it arrived at the controller but the value was null.

<div >
    <label  for="input-members">Selected Members</label>
    <select  id="members" name="members[]" multiple="multiple"> 
    </select>
 </div> 

 const _u = [];
 for (var i = 0; i <= users.length - 1; i  ) {
      console.log(users[i]);

     var j = {
         id: users[i]
     };

     _u.push(j);
}

var _f = JSON.stringify({
    pid: 0,
    members: _u
});

$.ajax({
     type: 'POST',
     url: '/User/Update/',
     traditional: true,
     data: _f,
     contentType: "application/json; charset=utf-8",
     dataType: 'json',
     headers: headers,
     
 [HttpPost]
 [Route("/User/Update")]
 [AllowAnonymous]
 public JsonResult Update_Data(string _f)

 // it arrived here, but _f value was null

what I missed?

CodePudding user response:

since you are using json content type, you have to add FromBody, and if you are using newtonsoft json, instead of string I would suggest to use JObject

public JsonResult Update_Data([FromBody]JObject _f)

if you still want to use your action with string you have to use this ajax (remove content type)


$.ajax({
     type: 'POST',
     url: '/User/Update/',
     traditional: true,
     data:{ "_f" : _f },
     dataType: 'json',
    
  • Related