I want to post data to my MMVC web api by using angular 2. But i don't know how to pass a object to my MVC API using angular. Any Help will be grateful.
My Service Code in Angular 2
@Injectable()
export class TaskService {
postitems(userId,username,userrole)
{
let data = {
"UserName": username,
"UserRole": userrole
}
let headers: {
'Content-Type': 'application/json; charset=utf-8', /*or whatever type is relevant */
'Accept': 'application/json'
}
//let body = JSON.stringify(data);
// let headers = new Headers({ 'Content-Type': 'application/json' ,'Accept': 'application/json'});
//let options = new RequestOptions({ headers: headers });
return this._http
.post('http://localhost:27353/api/Users',JSON.stringify(data), headers)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
My MVC Api Code
[ResponseType(typeof(User))]
public IHttpActionResult PostUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Users.Add(user);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = user.UserID }, user);
}
Model.cs
namespace WebApi.Models
{
using System;
using System.Collections.Generic;
public partial class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string UserRole { get; set; }
}
}