我想在我的 View 和 Controller 之间传递数据。我做错了什么,因为它不起作用。
JavaScript 前端代码:
$.ajax({
url: '@Url.Action("GetOid","SearchPerson")',
data: {oid : 1},
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
// return values
console.log("Success!" + data.oid);
},
error: function () { console.log('error!!'); }
});
C# Controller 代码:
int CustomerId=0;
[HttpPost]
public ActionResult GetOid(int Oid)
{
// some code here to assign the value to a global var.
CustomerId = Oid;
ViewBag.id = Oid;
return Json(new { oid = CustomerId });
}
});
最佳答案
对您的 ajax 数据属性进行此更改。它需要作为字符串传递。
data: JSON.stringify({ "Oid": 1 }),
您的 Controller 参数和数据参数也需要相同。区分大小写。
public ActionResult GetOid(int Oid)
最后如上所述,以 json 格式返回它。
return Json(new { oid = CustomerId });
关于c# - 在 JavaScript 和 C# Controller 之间传递数据 : Asp.Net MVC 4 Razor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642526/