【问题标题】:Angularjs http get from ASP.NETAngularjs http 从 ASP.NET 获取
【发布时间】:2016-08-13 07:35:46
【问题描述】:

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

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

  2. 如何在'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


【解决方案1】:

假设你在 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 传递给 getData 函数。

【讨论】:

    【解决方案2】:

    你应该将它作为参数传递给 $http get 调用

    $http({ method: 'GET', url: '/Home/GetData', params: { id: id } })
    

    【讨论】:

    • 这会将 id 作为查询参数附加。这将起作用,因为如果在 url 中找不到 id,MVC 将尝试在查询字符串中找到它。但是,这将导致不同的 url: /Home/GetData?id=123 而不是 /Home/GetData/123 。根据首选的 url,使用参数或将 id 直接附加到 url
    • @fikkatra 我知道..如果默认路由设置正确,就像你说的那样,它应该像你建议的那样..但在这种情况下,上面显然会起作用..
    • 没错。我只是想帮助 OP 在我们的解决方案之间做出明智的选择。
    • @fikkatra 如果您特别问我,那么我宁愿使用您在 WebAPI +1 yours 中建议的格式..
    猜你喜欢
    • 2016-10-02
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2017-06-29
    • 2014-04-01
    • 1970-01-01
    相关资源
    最近更新 更多