以下示例中,控制器名称为'TestController”,其中有一个名为'GetData”的动作方法,用于返回一个JsonResult:
public class TestController : Controller
{
public JsonResult GetData()
{
var data = new { Name = "John Smith", Age = 30 };
return Json(data, JsonRequestBehavior.AllowGet);
}
}
在视图中调用此方法时,应确保URL和参数正确无误,例如:
$.ajax({
url: "/Test/GetData",
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
}
});