通过Ajax与后端方法通信

时间:2015-08-13 09:13:17

标签: java html asp.net ajax angularjs

我正在尝试使用Ajax和AngularJS与方法进行通信,但我没有得到响应,警报输出undefined

Index.cshtml

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp">
// Displaying the table is working
    <div>
        <table class="table" ng-controller="UpdateController">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Country</th>
            </tr>
            <tr ng-repeat="c in cities">
                <td>{{c.Id}}</td>
                <td>{{c.City1}}</td>
                <td>{{c.Country}}</td>
            </tr>
        </table>
    </div>
// Here I add the controller for adding records -->
    <div ng-controller="AddRecord">
        <form id="form1" ng-submit="send()">
            <table>

                <tr>
                    <td>City: </td>
                    <td>
                        <input type="text" id="txtCity" ng-model="addCity" />
                    </td>
                </tr>
                <tr>
                    <td>Country: </td>
                    <td>
                        <input type="text" id="txtCountry" ng-model="addCountry" />
                    </td>
                </tr>

                <tr>
                    <td>
                        <input type="submit" id="btnSubmit" value="Submit" />
                    </td>
                </tr>

            </table>
        </form>
    </div>

    <script>
        var app = angular.module('myApp', []);

        app.controller('UpdateController', function ($scope, $http) {
            $http.get("http://localhost:50366/api/cities")
            .success(function (response) { $scope.cities = response });

        });        

        app.controller('AddRecord', function ($scope, $http) {
// Function responsible for communicating with backend  
            $scope.send = function () {    
                $.ajax({
                    type: "POST",
                    url: "AddCity.asmx.cs/PostCity",
                    data: "{'city':'" + $scope.addCity + "','country':'" + $scope.addCountry + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(msg.d);
                    },
                    error: function (msg) {
                        alert(msg.d);
                    }
                });
//Here is one I tried using text as the datatype:
            $.ajax({
                type: "POST",
                url: "AddCity.asmx/PostCity",
                data: "city=" + $scope.addCity + "&country=" + $scope.addCountry,
                dataType: "text",
                success: function (msg) {
                    alert(msg.d);
                },
                error: function (msg) {
                    alert(msg.d);
                }
            });

            };
        });

    </script>
</body>

</html>
使用我正在尝试访问的方法

AddCity.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AngularWebApi.Models;
using AngularWebApi.Controllers;

namespace AngularWebApi.Views
{
    /// <summary>
    /// Summary description for AddCity
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class AddCity : System.Web.Services.WebService
    {

        [WebMethod]
        public string PostCity(string city, string country)
        {
            City newCity = new City();
            newCity.City1 = city;
            newCity.Country = country;
            //Eventually I want to add the city to the database
            CitiesController controller = new CitiesController();

            controller.PostCity(newCity);

            return "Posted!";
        }
    }
}

Index.cshtml 位于Views/Home AddCity.asmx 位于Views。我也尝试使用url: "../AddCity.asmx/PostCity"

修改

我很快创建了一个新项目并进行了设置,完全相同的事情正在发生,以下是步骤:

  • 新的web api项目
  • 新的ADO.net实体数据模型并将其链接到我的数据库
  • 新的Web API 2控制器,其中包含使用Entity Framework的操作,从DB和实体中传递表格,这是我从后续步骤中获得的。

然后我编辑Index.cshtml以将API/CITIES中的XML显示为表格。这次我在项目的根目录中添加了我的服务,只是尝试使用HelloWorld $.ajax函数调用自动创建的POST

我确实在FF错误控制台中看到了警告。来自荷兰语的直译:{{1​​}}

此外,在{ajax调用中触发Cross-Origin-Request blocked: ....。 WebService没有被联系到。

这是我点击按钮时得到的完整回复:

error

修改

控制器中的POST方法:

<!DOCTYPE html>
<html>
    <head>
        <title>The resource cannot be found.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>The resource cannot be found.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. &nbsp;Please review the following URL and make sure that it is spelled correctly.
            <br><br>

            <b> Requested URL: </b>/Home/MyWebService.asmx/HelloWorld<br><br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408

            </font>

    </body>
</html>
<!-- 
[HttpException]: A public action method &#39;MyWebService.asmx&#39; was not found on controller &#39;AngularTutorial.Controllers.HomeController&#39;.
   at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
   at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

2 个答案:

答案 0 :(得分:1)

嗯,我想我明白了:你尝试创建一个新的POST-Method,但根据教程,City-Controller中已经有一个POST-Method:

  

通过单击Add,我们可以使用脚手架创建Cities Web API。创建的控制器类将具有用于城市表上所有CRUD 操作的Web API。

这意味着您只需将ajax调用发送到http://localhost:50366/api/cities

$.ajax({
       type: "POST",
       url: "http://localhost:50366/api/cities",
       data: "{'country':'" + country + "','name':'" + cityName + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
             alert(msg.d);
       },
       error: function (msg) {
             alert(msg.d);
       }
      });

确保只运行1个Web应用程序,这样可以避免不必要的问题。

顺便说一句。我不确定,如果控制器接受json,你可能需要将数据发送为xml ...

编辑: 我更新了json数据。您的城市对象有3个属性:countryidname。如果您发送POST请求即将创建新对象,因此您无需发送id

对于PUTDELETE(如果要实现此功能),您需要将id添加到网址: http://localhost:50366/api/cities/:id

EDIT2: 好的,xml应该是这样的:

data: "<City><Country>" + country + "</Country><Name>" + cityName + "</Name></City>",
不要忘记改变:

contentType: "application/xml; charset=utf-8",
dataType: "xml",

答案 1 :(得分:0)

不要使用ajax,即使它有用,你仍然会遇到问题,因为$.ajax调用不在Angular.js上下文中,你必须手动$scope.apply()返回的值。请改用角度$http服务。您可以在official documentation中找到如何使用它。它非常灵活,支持所有请求方法,查询参数,请求体等...还支持拦截器来处理您的所有请求。默认情况下,所有$http调用都返回promise(也使用.then()处理程序而不是成功和失败处理程序。)