简体   繁体   中英

How to send json object to the Controller JsonResult Method

I need to pass a JSON object that can have many elements, I tried it with the following code:

var app = new Vue({
   el: '#crearMetaCompuesta',
   data: {
      inputmin: 0,
      inputmax: 0,
      inputres: 0,
      rangos_creados: [{
         min: 1,
         max: 2,
         result: 3
      }]
   },
   methods: {
      additem: function() {

         let nuevoItem = {
            min: this.inputmin,
            max: this.inputmax,
            result: this.inputres,

         }

         this.rangos_creados.push(nuevoItem);
      },
      guardarMetaCompuesta: function() {

         console.log(JSON.stringify(this.rangos_creados));

         axios.post('@Url.Action("GuardarMetaCompuesta")', {
               msg: JSON.stringify(app.rangos_creados),
               id: 7
            }, {
               headers: {
                  'contentType': 'application/json; charset=utf-8'
               }
            }).then(function(response) {
               alert(response);
               console.log("--------->" + JSON.stringify(app.rangos_creados));
            })
            .catch(function(e) {
               console.log("---------> |" + e);
            });
      }
   }
})

the JSONResult Method:

public class MetasCompuestasClass{
    public string min { get; set; }
    public string max { get; set; }
    public string result { get; set; }
}


public JsonResult GuardarMetaCompuesta(MetasCompuestasClass msg, int id) {
  //here I put a breakpoint but the variable arrives null
    var x = 1;
    return Json(new { result = false, message = msg }, JsonRequestBehavior.AllowGet);
}

but the msg variable always arrives null.

How should I send the object or what 'headers' should I place so that the variable does not arrive null and I can save the elements of type MetasCompuestasClass ?

It looks like your rangos_creados object is an array, and you're expecting a single object in your Action.

Try with the Action signature like this:

public JsonResult GuardarMetaCompuesta(List<MetasCompuestasClass> msg, int id) {

Or, if you didn't mean to make that an array because you're always only passing one item to the api action, change rangos_creados declaration to an object, and map the nuevoItem properties to it, or just update the rangos_creados with the values instead of using nuevoItem and don't push it into the collection anymore. But that Depends on what you're trying to do.

It looks like you're sending app. instead of this.

JSON.stringify(app.rangos_creados) vs. JSON.stringify(this.rangos_creados)

Keep in mind that this may be a different context in this scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM