gpt4 book ai didi

javascript - Angularjs http 从 ASP.NET 获取

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:01:30 25 4
gpt4 key购买 nike

单击按钮 Get Data 后,我想获取员工列表。但是 JS 脚本不会调用 public JsonResult GetData

  1. 为什么js不调用public JsonResult GetData哪里出错了?

  2. 如何在'public JsonResult GetData(int id)'中传递参数?

家庭 Controller :

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');
});

}
});

索引.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>

最佳答案

假设您在 MVC 中保留默认路由配置,试试这个:

$scope.getData = function (id) {
$http({ method: 'GET', url: '/Home/GetData/' + id }).
success(function (data, status, headers, config) {
//$scope.Employees = [{ name: 'Jhon' }, { name: 'Rick' }];
}).
error(function (data, status, headers, config) {
alert('error');
});
};

并将 id 传递给 View 中的 getData 函数。

关于javascript - Angularjs http 从 ASP.NET 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com