Javascript 如何将json对象发送到控制器JsonResult方法
我需要传递一个可以包含许多元素的JSON对象,我使用以下代码进行了尝试:Javascript 如何将json对象发送到控制器JsonResult方法,javascript,c#,asp.net-mvc,Javascript,C#,Asp.net Mvc,我需要传递一个可以包含许多元素的JSON对象,我使用以下代码进行了尝试: var app = new Vue({ el: '#crearMetaCompuesta', data: { inputmin: 0, inputmax: 0, inputres: 0, rangos_creados: [{ min: 1, max: 2, result: 3 }] },
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,并且我可以保存类型为
MetaScompuesTaskClass
的元素?看起来您发送的是应用程序。而不是此。
JSON.stringify(app.rangos\u creados)
vs.JSON.stringify(this.rangos\u creados)
请记住,此在该场景中可能是不同的上下文。看起来您的
rangos\u creados
对象是一个数组,您希望在操作中使用单个对象
尝试使用如下操作签名:
public JsonResult GuardarMetaCompuesta(List<MetasCompuestasClass> msg, int id) {
publicjsonresult-GuardarMetaCompuesta(列表消息,int-id){
或者,如果您不想将其作为数组,因为您总是只将一个项传递给api操作,请将rangos\u creados
声明更改为一个对象,并将nuevoItem
属性映射到该对象,或者只使用值更新rangos\u creados
,而不使用nuevoItem,并且不要将其推送到集合中不再是离子了。
但这取决于您要做什么。我已经尝试过这种方法,但也不起作用:/能否监视开发人员工具的“网络”选项卡并查看发布的内容?如果消息缺失或为空,则指向JavaScript。请尝试
JSON.stringify({msg:this.rangos_creados,id:7})
我做到了,即使变量'id'也分配了实例的一个元素,'id'正确到达,'msg'一直为null,我在发送它之前打印它,以确保JavaScript{msg:JSON.stringify(this.rangos_creados)没有发送null,id:this.inputres}不,我的意思是字符串化整个对象,而不仅仅是msg
。比如:axios.post('@Url.Action(“GuardarMetaCompuesta”)',JSON.stringify({msg:this.rangos_creados,id:7}),…
否则msg
将是一个字符串,不会被强制转换为MetasCompuestasClass
。正在改进,'msg'已作为类型为'MetasCompuestasClass'的变量到达,但其元素到达空值,'min','max'和'result'是的!这对我很有用,非常感谢。这对我有用,谢谢!,还改变了json:axios.post('@Url.Action(“GuardarMetaCompuesta”)、json.stringify({msg:app.rangos_creados})的形成方法很好,很高兴能提供帮助。