【发布时间】:2016-08-13 07:35:46
【问题描述】:
单击按钮Get Data 后,我想获取员工列表。但是JS脚本不会调用public JsonResult GetData。
为什么js不调用
public JsonResult GetData哪里出错了?如何在'public JsonResult GetData(int id)'中传递参数?
家庭控制器:
namespace AngularJS.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetData(int id)
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee{Name="Jhon"});
employees.Add(new Employee{Name="Rick"});
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
public class Employee
{
public string Name { get; set; }
}
}
MyScript.js
var app = angular.module("myApp", []);
app.controller("calendarDemo", function($scope) {
$scope.count = 0;
$scope.getData = function () {
$http({ method: 'GET', url: '/Home/GetData' }).
success(function (data, status, headers, config) {
//$scope.Employees = [{ name: 'Jhon' }, { name: 'Rick' }];
}).
error(function (data, status, headers, config) {
alert('error');
});
}
});
Index.cshtml:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/CustomScripts/MyScript.js"></script>
<script src="~/Scripts/moment.js"></script>
<link rel="stylesheet/less" type="text/css" href="~/Scripts/CustomScripts/style.less">
<script src="~/Scripts/less-1.5.1.js" type="text/javascript"></script>
<li ng-repeat="employee in Employees">
{{employee.name}}
</li>
<button ng-click="getData()">Get Data</button>
【问题讨论】:
-
你能显示web api路由配置吗?
-
从哪里加载
angular.js?我看不到。 -
您是否尝试过直接从浏览器的地址栏调用 URL?它有效吗?如果在 mvc 操作处设置断点,它会被命中吗?
-
@fikkatra 这是一个控制器,而不是 ApiController。这将是常规路由,而不是 Web api 路由。
-
从 webmethod 中删除参数,然后使用相同的 $http 调用,如果它调用 webmethod 则意味着您也需要传递参数。传递参数使用 $http 对象的第三个参数。
标签: javascript asp.net angularjs