簡體   English   中英

Angularjs http來自ASP.NET

[英]Angularjs http get from ASP.NET

在點擊Get Data按鈕后,我想獲得員工列表。 但JS腳本不會調用public JsonResult GetData

  1. 為什么js不調用public JsonResult GetData哪里出錯?

  2. 如何在'public JsonResult GetData(int id)'中傳遞參數?

HomeController的:

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>

假設您在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函數。

您應該在$ http get call中將其作為參數傳遞

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM