在MVC 4中使用Json使用ajax的困难
本文关键字:ajax 使用 Json MVC | 更新日期: 2023-09-27 17:55:39
我正在尝试将一个变量传递给我的JsonResult,但她得到了nul,所以这是我的JsonResult和jQuery的代码
[HttpPost]
public JsonResult MostraTela(Teste testea)
{
return Json(new { success = true });
}
和:
var testea = JSON.stringify(dado);
$.ajax({
url: '/Home/MostraTela',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: {testea: testea },
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
},
});
Agora eu fui tentar passar uma model e esta esta recebendo nulo novamente alguma ideia do que pode ser?我递增数据:{testea:testea},错误,如果我步进数据:testea,在我的JsonResult中一切都为空
我的模型:
public class Teste
{
public int idteste { get; set; }
public string name { get; set; }
public int age { get; set; }
public string birthday { get; set; }
public string salary { get; set; }
}
尝试为 testea
变量指定名称,以确保操作方法将其分配给相同的命名参数,如下所示:
$.ajax({
url: url,
type: "post",
data: { testea: testea },
dataType: 'json',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
由于目标方法的签名是字符串,请尝试将 123 作为字符串传递,例如。
var testea = JSON.stringify("123");
如果要传递 JSON,请将content-type
设置为 application/json
。
$.ajax({
type: 'POST',
url: '@Url.Action("MostraTela", "Home")',
data: { Id: 1, Name: 'Im a complex object' },
success: function (data) {
alert(data.success);
},
dataType: 'json',
contentType: 'application/json, charset=utf-8',
});
控制器:
[HttpPost]
public JsonResult MostraTela(MyModel model, FormCollection collection)
{
return Json(new { success = true });
}
类:
public class MyModel
{
public string Name { get; set; }
public int Id { get; set; }
}