我如何使用Angular将来自FORM输入的值发布到WebApi

时间:2018-08-13 19:54:51

标签: angularjs asp.net-web-api

<div class="input-group col-md-12">
    <input type="text" class="form-control input-lg"/>
    <span class="input-group-btn">
        <button class="btn btn-info btn-lg" type="button">
            <i class="glyphicon glyphicon-search"></i>
        </button>   
    </span>
</div>

基本上,我试图在按钮单击WebAPI时发布输入字段的值

我的WebAPI方法

public string Post([FromBody]dynamic value)
{
    return some value from form here; // JToken
}

2 个答案:

答案 0 :(得分:0)

您需要按如下所示将HTML表单包裹在代码中

<form novalidate name="frm1">
    <div class="input-group col-md-12">
        <input type="text" class="form-control input-lg" name="firstName" ng-model="user.firstName" />
        <input type="text" class="form-control input-lg" name="lastName" ng-model="user.lastName" />
        <span class="input-group-btn">
                <button class="btn btn-info btn-lg" type="button" ng-click="submit($event, user)">
                    <i class="glyphicon glyphicon-search"></i>
                </button>   
            </span>
    </div>
</form>

使用ng-model指令绑定您的每个输入,并且您的控制器应进行如下修改

angular.module('main').controller('someController', function($scope, $http) {
    $scope.user = {
        firstName: null,
        lastName: null
    };

    $scope.submit = function($event, user) {
        $http.post('api/users', user)
        .then(function(response) {
            console.log('success');
        }).catch(error) {
            console.log(error);
        }
    };
});

答案 1 :(得分:0)

here am giving the Code example for getting the users list from the table Users
Step 1:
public JsonResult UserLogin()
        {
            using (Codesnnip Db = new Codesnnip())
            {
                var user = Db.users.ToList();
                return Json(user, JsonRequestBehavior.AllowGet);
            }
        }

Step 2: step in to angular js
    Step 2.1 create a angular anglar app

    var SampleApp = angular.module('SampleApp',[]);

    Step 2.2 create controller for the View

    SampleApp.controller('HomeCtrl',['$scope',function($scope){

    }]);

    step 2.3 create a service to getting the users data

    SampleApp.factory('userData',function($http){
        var fac = {};
        fac.GetUsers = function(){
            return $http.get('/Home/UserLogin'); // Controllername/action
        }
        return fac;
    });

    after creating the service use this service in the controller like this

    step 2.4
        in html

        <button ng-click="getUserdata()">GetAllUsers</button>

    SampleApp.controller('HomeCtrl',['$scope','userData',function($scope,userData){
        $scope.usersList = null;
        $scope.getUserdata = function(){
            userData.GetUsers().then(function(d){
                $scope.usersList = d.data;
            })
        }
    }]);