Angular 2 to post data to asp.net mvc controller - c#

I am trying to post data from angularjs2 to asp.net mvc controller.
The actual issue is that when I am trying with it then
See how am I trying ?
this is the typescript ---
save(company: Company): Observable<boolean> {
let headers = new Headers({ 'Content-Type': 'application/json' });
this._http.post(this._postUrl, /*JSON.stringify(*/company/*)*/, { headers: headers })
.subscribe(
(data) => {
console.log('Response');
new Observable<true>()
},
(err) => { console.log(err); new Observable<false>(); },
() => console.log('Complete')
);
return new Observable<false>();
}
onSignUpClicked(message: string): void {
this._service.save(this.company).subscribe(
res => console.log(res),
error => this.errorMessage = <any>error
);
this is the typescript class:
import { Address } from '../shared/Address';
import { Contact } from '../shared/Contact';
export class Entity {
Id: string;
InsertionTime: Date;
InsertUserId: number;
IsDeleted: boolean;
IsLocked: boolean;
UpdateTime: Date;
UpdateUserId: number;
}
export class Company extends Entity {
Name: string;
Address: Address;
Contact: Contact;
Password: string;
ConfirmPassword: string;
UserName: string;
RegistrationDate: Date;
IsActive: boolean;
NextBillingDate: string;
TransactionLimit: number
}
and C# class
public class Company : Entity
{
public string Name { get; set; }
public Address Address { get; set; }
public Contact Contact { get; set; }
public string Password { get; set; }
public string UserName { get; set; }
public Image LogoImage { get; set; }
public DateTime RegistrationDate { get; set; }
public DateTime LastUpdated { get; set; }
public bool IsActive { get; set; }
public DateTime NextBillingDate { get; set; }
public Int64 TransactionLimit { get; set; }
}
public class Entity : IEntity
{
public Entity()
{
Id = Guid.NewGuid();
InsertionTime = DateTime.Now;
IsDeleted = false;
IsLocked = false;
}
public Guid Id
{
get;set;
}
public DateTime InsertionTime
{
get;set;
}
public int InsertUserId
{
get; set;
}
public bool IsDeleted
{
get; set;
}
public bool IsLocked
{
get; set;
}
public DateTime? UpdateTime
{
get;set;
}
public int? UpdateUserId
{
get; set;
}
}
any help appreciated

Here is a basic call to the server from an ng2 app:
getMeSomeServerData(someVar: string): Promise < IGenericRestResponse > {
let headers = new Headers();
headers.append("Content-Type", "application/json");
let url = "/getMeSomeServerData";
let post = this.http.post(url, JSON.stringify(someVar), {
headers: headers
}).map(response => response.json());
return post.toPromise();
}
And on the asp.net mvc backend:
// this of course goes within a controller
[HttpPost()]
[Route("getMeSomeServerData")]
public JsonNetResult GetMeSomeServerData(string someVar) {
GenericRestResponse response = new GenericRestResponse();
response.Error = false;
// do somthing
return new JsonNetResult(response);
}
JsonNetResult is simply a custom method for serializing an object into json. Obviously, you can modify someVar and IGenericRestResponse to your own needs.
On the client side, you also can return an Observable instead of a promise; the promise method is more familiar to me, so I use it unless I need some of the special functionality of an Observable.

Related

.net Core 2.0 Web API - Newtonsoft.Json.JsonSerializationException - IQueryable

I have two separate .net core applications, Web API and client. I get the model using:
public IEnumerable<OhaMedication> GetOhaMedication()
{
return _context.OhaMedication;
}
The model:
public class OhaMedication
{
public int OhaMedicationId { get; set; }
public string Phn { get; set; }
public int OhaTypeId { get; set; }
public int FrequencyId { get; set; }
public MedFrequancy Frequency { get; set; }
public OhaType OhaType { get; set; }
}
public class OhaType
{
public OhaType()
{
OhaMedication = new HashSet<OhaMedication>();
}
public int OhaTypeId { get; set; }
public string Name { get; set; }
public ICollection<OhaMedication> OhaMedication { get; set; }
}
public class MedFrequancy
{
public MedFrequancy()
{
OhaMedication = new HashSet<OhaMedication>();
}
public int FrequencyId { get; set; }
public string Frequency { get; set; }
public ICollection<OhaMedication> OhaMedication { get; set; }
}
In the client I use the following to get the data:
public IQueryable<OhaMedication> GetohaMedication()
{
var dir = _session.GetString(SessionsKeys.Directory);
bool connection = InternetConnection.Check(_webApiData.WebApiitems.Url);
if (connection)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_webApiData.WebApiitems.Url);
MediaTypeWithQualityHeaderValue contentType =
new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
HttpResponseMessage response = client.GetAsync("/OhaMedications").Result;
string stringData = response.Content.ReadAsStringAsync().Result;
IQueryable<OhaMedication> data = JsonConvert.DeserializeObject<IQueryable<OhaMedication>>(stringData);
return data;
}
}
else
return _context.OhaMedication;
}
I need to use IQueryable to use include as follows:
var ohaMed = GetohaMedication().Where(x => x.Phn == phn).Include(o => o.Frequency)
.Include(o => o.OhaType).ToList();
I get the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot create and populate list
type System.Linq.IQueryable`1[WebUI.Data.DataModels.OhaMedication].
Path '', line 1, position 1.'
It cannot create an interface because doesnot know which type it actually should use.
Try:
JsonConvert.DeserializeObject<List<OhaMedication>>(stringData).AsQueryable()

Back end cant see front end post like nulls

I have c# controller
[EnableCors("AllowSpecificOrigin")]
[Route("AddCar"), HttpPost]
public async Task<CarStatus> AddCar(Car car)
{
return _carService.AddCar(car);
}
and Angular services
AddCar(addCarModel: CarModel): Promise<CarStatus>{
const headers = new Headers({ 'Content-Type': 'application/json'});
return this.http.post("http://localhost:54116/AddCar", JSON.stringify({RegistrationNumber : addCarModel.RegistrationNumber, TypeOfCar: addCarModel.TypeOfCar, Model: addCarModel.Model,
YearOfProduction: addCarModel.YearOfProduction, Power: addCarModel.Power, vinNumber: addCarModel.VinNumber, Factory: addCarModel.Factory, CarReviewDate: addCarModel.CarReviewDate ,
OcEndDate: addCarModel.OcEndDate, Insurer: addCarModel.Insurer,UdtElevatorReviewWhen : addCarModel.UdtElevatorReviewWhen, UdtElevatorReviewFrom: addCarModel.UdtElevatorReviewFrom,
TachografReviewWhen: addCarModel.TachografReviewWhen, TachografReviewFrom: addCarModel.TachografReviewFrom,FaultList: null ,Owner: addCarModel.Owner}), { headers: new Headers({ 'Content-Type': 'application/json' }) }).toPromise().
then(response => {
var y = response.json();
return y;
});
and AddCar.ts
import { Component, OnInit } from '#angular/core';
import { CarService } from '../../services/car.service';
import { NgForm } from "#angular/forms";
#Component({
selector: 'app-add-car',
templateUrl: './add-car.component.html',
styleUrls: ['./add-car.component.css']
})
export class AddCarComponent implements OnInit {
constructor(private carService: CarService) { }
ngOnInit() {
}
onSubmit(form: NgForm): void {
console.log(form.value);
this.carService.AddCar(form.value);
}
}
My Angular CarModel
export class CarModel{
RegistrationNumber: string;
CarReviewDate : Date;
Factory: string;
Insurer: string;
Model : string;
OcEndDate: Date;
Owner : string;
Power : number;
TypeOfCar: string;
YearOfProduction: number;
VinNumber: string;
UdtElevatorReviewFrom: Date;
UdtElevatorReviewWhen: Date;
TachografReviewFrom: Date;
TachografReviewWhen: Date;
FaultList : Fault[];
}
My c# Car Model
public class Car
{
[Key]
public string RegistrationNumber { get; set; }
public string TypeOfCar { get; set; }
public string Model { get; set; }
public int YearOfProduction { get; set; }
public int Power { get; set; }
public string VinNumber { get; set; }
public string Factory { get; set; }
public DateTime CarReviewDate { get; set; }
public DateTime OcEndDate { get; set; }
public string Insurer { get; set; }
public DateTime? UdtElevatorReviewWhen { get; set; }
public DateTime? UdtElewatorReviewFrom { get; set; }
public DateTime? TachografReviewWhen { get; set; }
public DateTime? TachografReviewFrom { get; set; }
public List<Fault> FaultList { get; set; }
public string Owner { get; set; }
In back end i have braekpoint and connection is good, but all values in sending car are nulls. Why? and how can i fix that?
link to project https://github.com/BialekM/TransportApp
network status https://imgur.com/QRZ4KJw
C# inform me the all values are null without 2 datetime wchick cant be null

Parsing [FromBody] JSON: model null

I'm trying to parse some json in my action which will then do things with it. However I keep getting null as my model instead of the filled out model.
This is the json I'm trying to parse:
{
"sameLanguages":true,
"sameDeadlines":true,
"sameDeliverables":false,
"quotations":[
{
"name":"zasd",
"deliverable":"538184e1-9a62-4ce9-baa7-ed746f267a9a",
"subtitleAssignments":{
"languageCombinations":[
{
"from":"d177b276-8f10-472f-84c6-f2ef59052a09",
"to":"d177b276-8f10-472f-84c6-f2ef59052a09",
"startDate":"19-09-2017",
"endDate":"19-09-2017"
}
],
"amount":12
},
"translationAssignments":{
"languageCombinations":[
]
}
}
]
}
This is my action:
[HttpPost]
public IActionResult Add([FromBody] SubmitQuotationsModel model)
{
//Do things...
return View();
}
These are my models:
public class SubmitQuotationsModel
{
public bool SameLanguages { get; set; }
public bool SameDeadlines { get; set; }
public bool SameDeliverables { get; set; }
public List<SubmitQuotationModel> Quotations { get; set; } = new List<SubmitQuotationModel>();
}
public class SubmitQuotationModel
{
public string Name { get; set; }
public string Deliverable { get; set; }
public List<AssignmentModel> SubtitleAssignments { get; set; }
public List<AssignmentModel> TranslationAssignments { get; set; }
}
public class AssignmentModel
{
public List<LanguageCombinationModel> LanguageCombinations { get; set; }
public int Amount { get; set; }
}
public class LanguageCombinationModel
{
public string From { get; set; }
public string To { get; set; }
public DateTimeOffset StartDate { get; set; }
public DateTimeOffset EndDate { get; set; }
}
I am sending the json from my knockout/typescript script as such:
fetch('/Quotation/Add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: this.toJSON()
});
public toJSON(): string {
let model = {
sameLanguages: this.step1().sameLanguages(),
sameDeadlines: this.step1().sameDeadlines(),
sameDeliverables: this.step1().sameDeliverables(),
quotations: this.step2().quotations().filter((q) => q.isFilledIn()).map((q) => {
return {
name: q.name(),
deliverable: q.selectedDeliverable().id,
subtitleAssignments: this.getAssignmentModel(q.subtitleAssignmentGroup()),
translationAssignments: this.getAssignmentModel(q.translationAssignmentGroup())
}
})
};
return ko.toJSON(model);
}
private getAssignmentModel(model: AssignmentGroupModel) {
return {
languageCombinations: model.assignments().map((a) => {
return {
from: a.fromLanguage().value,
to: a.toLanguage().value,
startDate: a.startDate().format('DD-MM-YYYY'),
endDate: a.endDate().format('DD-MM-YYYY')
}
}),
amount: model.amount()
}
}
I'm not getting any exceptions, the model parameter just remains null. I have found that if I comment out the SubtitleAssignments and TranslationAssignments in SubmitQuotationModel, it deserializes the other parts of the json just fine. But I can't figure out why it won't deserialize with those two ...Assignments declarations not commented out.
SubtitleAssignments and TranslationAssignments aren't lists in the json but they are lists in the models. They just need to be AssignmentModel and not List<AssignmentModel>

Rest API- How to get Json API Request call and send Json Response using c#?

My requirements are
create API to get the user information(JSON request) from other system, update those information to database.
After update want to send the JSON response back.
Please help me to achieve this.
My controller:
namespace CT.API.User
{
public class UserController : CTControllerBase
{
//API
[AllowAnonymous]
public JsonResult USerApiTest()
{
// to handle the code
}
}
}
Request Details:
{"REQLEN":4,"REQDTL":[{"ID":"48490","UserName":"Test1","Password":"Test1"},{"ID":"48491","UserName":"Test2","Password":"Test2"}]}
Reponse Details:
{"RESLEN":4,"RESDTL":[{"ID":"48490","Status":"Success"},{"ID":"48491","Status":"Fail"}]}
If I understand you, this is what you Need:
namespace CT.API.User
{
public class UserController : CTControllerBase
{
//API
[AllowAnonymous]
[HttpPost]
public ResponseModel USerApiTest([FromBody] RequestModel request)
{
// to handle the code
ResponseModel res = new ResponseModel ();
List<UserResult> results = new List<UserResult>();
foreach( var user in request.ReqDtl)
{
if(//Status should be Success)
{
results.Add( new UserResult{ ID=user.ID,Status = "Success"};
}
else
{
results.Add(new UserResult{ ID=user.ID, Status = "Fail"};
}
}
res.ResDtl= results.ToArray();
res.ResLen=request.ReqLen;
return res;
}
}
public class RequestModel
{
public int ReqLen { get; set;}
public User[] ReqDtl { get; set; }
}
public class ResponseModel
{
public int ResLen { get; set; }
public UserResult[] ResDtl { get; set; }
}
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class UserResult
{
public int ID { get; set; }
public string Status { get; set; }
}
}

Angularjs : Post form data with an image to Web API backend

I am trying to post a form data that includes an image from Angularjs client to a Web API backend, but gets an error:
"Could not create an instance of type System.Web.HttpPostedFileBase. Type is an interface or abstract class and cannot be instantiated. Path 'ProfileImage', line 1, position 299."
My angular code is
$scope.RegisterUser = function () {
$http({
method: 'POST',
url: 'http://localhost:2434/api/Account/BrandRegistration/',
data: $scope.brandForm,
file : $scope.brandForm.ProfileImage
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log("libin");
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
My web api method is
public async Task<IHttpActionResult> PostBrandRegistration(BrandRegistration brandVM)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("brand"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "brand";
roleManager.Create(role);
}
if (!roleManager.RoleExists("influencer"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "influencer";
roleManager.Create(role);
}
var user = new ApplicationUser()
{
UserName = brandVM.Email,
Email = brandVM.Email
};
var fileName = "";
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
if (file != null && file.ContentLength > 0)
{
fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/App_Data/ProfileImage"),
fileName
);
file.SaveAs(path);
}
user.BrandUser = new BrandUser()
{
FullName = brandVM.FullName,
ContentType = brandVM.ContentType,
Description = brandVM.Description,
URL = brandVM.URL,
ContactPerson = brandVM.ContactPerson,
Position = brandVM.Position,
PhoneNumber = brandVM.PhoneNumber,
ContactEmail = brandVM.Email,
Address = brandVM.Address,
MarketPlace = brandVM.MarketPlace,
Campaigns = brandVM.Campaigns,
InfluencerRating = brandVM.InfluencerRating,
ProfileImage = fileName
};
user.BankDetail = new BankDetail()
{
AccountNumber = brandVM.AccountNumber,
AccountName = brandVM.AccountNumber,
IRD = brandVM.IRD,
GST = brandVM.GST
};
IdentityResult result = await UserManager.CreateAsync(user, brandVM.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
else
{
await this.UserManager.AddToRoleAsync(user.Id, "brand");
return Ok();
}
}
And my View Model is
public class BrandRegistration
{
public string Email { get; set; }
public string Password { get; set; }
public string PasswordConfirmation { get; set; }
public string FullName { get; set; }
public string ContentType { get; set; }
public HttpPostedFileBase ProfileImage { get; set; }
public string Description { get; set; }
public string URL { get; set; }
public string ContactPerson { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public int PhoneNumber { get; set; }
public string ContactEmail { get; set; }
public string Address { get; set; }
public string AccountNumber { get; set; }
public string AccountName { get; set; }
public string IRD { get; set; }
public string GST { get; set; }
public bool MarketPlace { get; set; }
public bool Terms { get; set; }
public double InfluencerRating { get; set; }
public int Campaigns { get; set; }
}
I really appreciate if someone can advice me of where i have gone wrong.
I'm not familiar with .NET, but you definitely should use form data on the client side.
var fd = new FormData();
fd.append('file', $scope.brandForm.ProfileImage);
fd.append('data', $scope.brandForm)
$http({
method: 'POST',
url: 'http://localhost:2434/api/Account/BrandRegistration/',
data: fd
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})

Categories

Resources