【发布时间】:2015-07-30 11:37:30
【问题描述】:
在将 angularjs 与 asp.net mvc 结合时遇到问题。我正在使用角度路由在 ng-view 指令中渲染 html 部分视图。在这里,我使用 angular $locationProvider 省略了 angularjs 默认 #(hash) 导航行为。一切正常,我可以正确导航到每个局部视图,每个 $scope 对象也可以正常工作。但有一个问题。 $http.post 方法不会调用 aps.net 控制器操作。它什么也不做。调试点没有命中。但是$http.get 工作得很好,它可以将数据检索为 json 对象。但是 $http.post 在 ng-view 之外运行良好。我在这里缺少什么。请帮忙。
asp.net RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "RoutesDemo",
url: "{*catchall}",
defaults: new { controller = "Home", action = "Index" });
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
首页/index.chtml
<html ng-app="MyApp" ng-controller="MyController">
<head>
<meta charset="utf-8">
<base href="/">
</head>
<body>
<h1>{{heading}}</h1>
<ul>
<li><a href="/routeOne">Route One</a></li>
<li><a href="/routeTwo">Route Two</a></li>
<li><a href="/routeThree">Route Three</a></li>
</ul>
<div ng-view></div>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Scripts/app.js"></script>
</body>
</html>
one.html
<h3>One</h3>
<br />
<input type="text" ng-model="item" />
<input type="button" ng-click="postitem()" value="Send"/>
两个.html
<h3>Two</h3>
three.html
<h3>Three</h3>
app.js
var app = angular.module('MyApp', ['ngRoute']);
app.config(function ($routeProvider,$locationProvider) {
$routeProvider
.when('/routeOne', {
templateUrl: 'partials/one.html',
controller: 'MyController'
})
.when('/routeTwo', {
templateUrl: 'partials/two.html',
controller: 'MyController'
})
.when('/routeThree', {
templateUrl: 'partials/three.html',
controller: 'MyController'
});
$locationProvider.html5Mode(true);
});
app.controller('MyController', function ($scope,$http) {
$scope.heading = "Page Heading";
$scope.item = "Mango";
$scope.postitem = function () {
$http.post('/RoutesDemo/addMe', { foo : 'bar' }).success(function (response) {
});
}
})
RoutesDemoController
public class RoutesDemoController : Controller
{
[HttpPost]
public void addMe(string foo)
{
string fruit = foo;
}
}
【问题讨论】:
-
尝试为控制器中的方法添加HttpPost属性。
-
@rnofenko 不工作
-
浏览器对
POST /RoutesDemo/addMe的网络响应显示什么 -
@Jasen 响应是我的 index.cshtml 代码
标签: javascript c# asp.net-mvc angularjs