Web API POST方法从Angular2服务调用获取空值

时间:2017-06-13 16:49:31

标签: asp.net-web-api angular2-services

我创建了HTMLTS组件。我给了服务TS代码和API代码。请帮忙。我尝试了很多选项来玩内容类型和接受标题,但没有运气。我一直在为我的Web API方法获取NULL值。

HTML页面:

<h1>User Preference</h1>

<div class="panel panel-default panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">Edit User</h3>
    </div>
    <div class="panel-body">
        <div class="col-md-6" *ngIf="oneUser">
            <form autocomplete="off" #userForm="ngForm" (submit)="updateUserInfo(userForm.value)">
                <div class="form-group">
                    <label for="msUserID">MS User ID:</label>
                    <input id="msUserID" readonly type="text" class="form-control" 
                           [(ngModel)] = "oneUser.msUserId" name="msUserId"
                           placeholder="Enter MS User ID..."/>
                </div>
                <div class="form-group">
                    <label for="firstName">First Name:</label>
                    <input id="firstName" readonly type="text" class="form-control" 
                           [(ngModel)] = "oneUser.firstName" name="firstName"
                           placeholder="Enter First Name.." />
                </div>
                <div class="form-group">
                    <label for="lastName">Last Name:</label>
                    <input id="lastName" readonly type="text" class="form-control" 
                           [(ngModel)] = "oneUser.lastName" name="lastName"
                           placeholder="Enter Last Name..." />
                </div>
                <div class="form-group">
                    <label for="userReportAccess">User Report Access:</label>
                    <select [(ngModel)]="oneUser.userReportAccess" class="form-control" name="userReportAccess">
                        <option value=""></option>
                        <option value="0">false</option>
                        <option value="1">true</option>
                    </select>
                </div>

                <button type="submit" class="btn btn-primary">Update</button>
            </form>
        </div>
    </div>
</div>

COMPONENT:

import { Component, OnInit } from '@angular/core'

import { UserDetails } from "../shared/user-details.model";
import { UserService } from "../shared/user.service";

@Component({
    selector: "user-one",
    templateUrl: "./user.component.html"
})
export class UserComponent implements OnInit {
    public oneUser: UserDetails;
    testVa: string = "TEST";

    constructor(private userService: UserService) {
    }

    ngOnInit() {
        this.userService.getOneUserDetails()
            .then(user => this.oneUser = user);
        console.log("DATA" + JSON.stringify(this.oneUser));
    }

    updateUserInfo(userForm) {
        alert("UPDATE method call" + JSON.stringify(userForm));
        //data: UserDetails = {
        //    msUserId: userForm.msUserId,

        //};
        console.log("Update data" + JSON.stringify(userForm));
        let data: UserDetails = {
            msUserId: userForm.msUserId,
            firstName: userForm.firstName,
            lastName: userForm.lastName,
            userReportAccess: userForm.userReportAccess
        };
        this.userService.updateUserDetails(data);
    }
}

SERVICE:

import { Injectable, Inject } from '@angular/core';
import { Http, Response, RequestOptions, Headers, RequestMethod } from '@angular/http';
import 'rxjs/Rx'; 
import 'rxjs/Observable';

import { UserDetails } from './user-details.model';
import { Observable } from "rxjs/Rx";

@Injectable()
export class UserService {
    private _originalUrl: string;
    public headers: Headers;

    constructor(private http: Http, @Inject('ORIGIN_URL') originUrl: string) {
        this._originalUrl = originUrl;

        this.headers = new Headers();  
        this.headers.append('Content-Type', 'application/json') 
        this.headers.append('Accept', 'application/json');

        console.log("OriginalURL" + originUrl);
    }

    getOneUserDetails() {
        return this.http.get(this._originalUrl + '/api/PAUser/GetOneUserDetails')
            .map(response => response.json() as UserDetails)
            .toPromise();
    }

    updateUserDetails(data) {
        let headers = new Headers({
            'Content-Type': 'application/json;charset=utf-8',
            'Accept': 'application/json'
        });     

        let options = new RequestOptions({ headers: headers, method: RequestMethod.Post });//, method: "post"
        console.log("Service data" + JSON.stringify(data));
        return this.http.post(this._originalUrl + '/api/PAUser/UpdateOneUserDetails', JSON.stringify(data))
            .map(response => response.json() as UserDetails)
            .toPromise();
    }
}

WEB API:

[HttpPost("[action]")]

    public void UpdateOneUserDetails([FromBody] PA_Users userDetails)
        {
            if (userDetails != null)
            {
                var userFind = _context.PA_Users.Where(x => x.MsUserId.Equals(userDetails.MsUserId)).ToList();

                if (userFind.Count > 0)
                {
                    userFind[0].UserReportAccess = userDetails.UserReportAccess;
                    _context.SaveChanges();
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

这可能会这样做......不确定你是否已经尝试过这个,你可以尝试将“DataContractAttribute”添加到类中,将“DataMemberAttribute”添加到“PA_Users”类的所有成员/属性中吗?

希望这有帮助! 谢谢, Bhadhri