如何将 json 对象发送到控制器 JsonResult 方法



我需要传递一个可以有很多元素的JSON对象,我用以下代码尝试了它:

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);
});
}
}
})

JSONResult 方法:

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);
}

msg变量始终到达 null。

我应该如何发送对象或应该放置哪些"标头",以便变量不会到达 null 并且可以保存类型MetasCompuestasClass的元素?

看起来您的rangos_creados对象是一个数组,并且您希望操作中包含单个对象。

尝试使用如下所示的操作签名:

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

或者,如果您不想将其设置为数组,因为您始终只将一个项目传递给 api 操作,请将rangos_creados声明更改为对象,并将nuevoItem属性映射到它,或者只是使用值更新rangos_creados而不是使用 nuevoItem 并且不再将其推送到集合中。 但这取决于你想做什么。

看起来您正在发送应用程序。 而不是这个。

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

请记住,在这种情况下,这可能是不同的上下文。

最新更新