How to perfrom WEBAPI Post call from react Js? - reactjs

Its already asked question. But still i didnt clear.
I have to call POST Method of WEBAPI in reactjs. But i have created model in webapi. So i want to know how to pass the model data to post call in reactjs.
Model :
public class EmployeeModels
{
public int Id { get; set; }
public string name { get; set; }
public string mobile { get; set; }
public string email { get; set; }
public string dept { get; set; }
public string erole { get; set; }
}
My WEBAPI Post Method :
//Insert new Employee
public IHttpActionResult CreateNewEmployee(EmployeeModels emp)
{
using (var ctx = new Employee())
{
ctx.tempemp.Add(new tempemp()
{
Id = emp.Id,
name = emp.name,
mobile = emp.mobile,
erole = emp.erole,
dept = emp.dept,
email = emp.email
});
ctx.SaveChanges();
}
return Ok();
}
Now i should want to post Employeemodel from reactjs. Kindly give any suggestions.

I have already given answer:
let employee={
Id:1,
name:'abc',
mobile:123456,
email:'abc#abc.com',
dept:'IT',
role:'Developer'
}
fetch('https://mywebsite.com/CreateNewEmployee/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(employee)
})
.then(function(resp){
// your response
})

You can use axios library.
npm install axios --save
and then:
axios.post('/CreateNewEmployee/', {
Id:1,
name:'abc',
mobile:123456,
email:'abc#abc.com',
dept:'IT',
role:'Developer'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Related

Postman POST working but AngularJS post throwing 404

I'm just trying to pass some basic form data through to a web-api via AngularJS $http.
here is the function that called to send data to the API:
$http({
url: "/Portal/GenerateTimeSheets",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
data: angular.toJson($scope.placementForm),
}).then(function (response) {
}), function(response) {
};
Note: if I breakpoint and copy and paste the $scope.placementForm data into postman it works completely fine, but going through a browser is throwing errors.
Here is my api:
[HttpPost]
public void GenerateTimeSheets([FromBody]PlacementModel placement)
{
Console.WriteLine("STUB");
}
and the Placement Model:
[JsonProperty(PropertyName = "candidateName")]
public string CandidateName { get; set; }
[JsonProperty(PropertyName = "clientName")]
public string ClientName { get; set; }
[JsonProperty(PropertyName = "jobTitle")]
public string JobTitle { get; set; }
[JsonProperty(PropertyName = "placementStartDate")]
public string StartDate { get; set; }
[JsonProperty(PropertyName = "placementEndDate")]
public string EndDate { get; set; }
[JsonProperty(PropertyName = "frequency")]
public string TimeSheetFrequency { get; set; }
404 Usually denotes that the url of the request is wrong, You are missing something in the url. Validate your url with the backend. Hope it helps

sending byteArray in a JSON body via angularjs http request

I want to send a post request in which the body of request is a JSON included two attributes , one of them is canvas information generated with fabricjs and the second one is a byteArray of project thumbnail. the problem is that, when I send the request , I receive null in server side.
var dataURI = this.getDataUrl($rootScope.imageType, $rootScope.imageQuality);
var strImage = dataURI.replace(/^data:image\/[a-z]+;base64,/, "");
var byteArray = covertBase64ToByteArray(strImage);
var data = {
data: {
name: name,
state: canvas.fabric.toJSON(['selectable', 'name']),
zoom: canvas.zoom,
canvasWidth: width,
canvasHeight: height,
},
typeArray: byteArray
};
$http({
method: "POST",
url: _url,
data: JSON.stringify(data),
processData: false,
transformRequest: [],
contentType: 'application/json',
})
backend Code in .Net
public IHttpActionResult InsertOrUpdateUILayout(long user_Id, long layout_Id, int userLayout_Id, int? layoutType_Id, UserlayoutContentVM data)
{
// back end code here
}
public class UserlayoutContentVM
{
public object data { get; set; }
//public string base64Image { get; set; }
public byte[] typeArray{ get; set; }
}
When posting data to the backend api you need to tell the method to read the data from the request body.
This can be done with the FromBody attribute which will map the body data to the define model.
So add all properties to one model
public class UserlayoutContentVM
{
public long user_Id { get; set; }
public long layout_Id { get; set; }
public int userLayout_Id { get; set; }
public int? layoutType_Id { get; set; }
public object data { get; set; }
public byte[] typeArray{ get; set; }
}
Then make sure the client send all data in the same structure and use the FromBody attribute in the controller method to read the values
public IHttpActionResult InsertOrUpdateUILayout([FromBody]UserlayoutContentVM data){ }

Angular js posting object to web API is null

I am posting form data to webAPI and one of object has boolean value(i.e from checkbox; Deviceselected has boolean values here in code).this object returns null in my api controller.
I tried declaring Desktop and Mobile as string in controller.That did not fix as well.
What am i missing in here?
I'm able to post other data except Deviceselected
Angualrjs controller code
$scope.SendData = function (Data) {
var GetAll = new Object();
GetAll.Redirection = Data.redirection;
GetAll.Deviceselected = new Object();
GetAll.Deviceselected.Desktop = Data.devSelected.desktop;
GetAll.Deviceselected.Mobile = Data.devSelected.mobile;
GetAll.Protocol = Data.protocol;
$http({
url: "http://localhost:61352/api/Market",
dataType: 'json',
method: 'POST',
data: GetAll,
headers: {
"Content-Type": "application/json"
}
}).then(successCallback, errorCallback);
};
})
Web API code
public class SubmitData
{
public string Redirection { get; set; }
public Deviceselected deviceSelected;
public string Protocol { get; set; }
}
public class Deviceselected
{
public Boolean Desktop { get; set; }
public Boolean Mobile { get; set; }
}
[HttpPost]
public string sendData(HttpRequestMessage request,[FromBody] SubmitData marketModel)
{
return "Data Reached";
}
Apparently it works with the same logic.1)Cleared cache 2)Run API and then load HTML

angularjs $http post object always null

I'm trying to send an object to the backend with an $http post, but one of the parameters is always null. I'm formatting the dto in the same way when saving a new object and that works fine, but when I try to call the update function it's not working. What am I missing?
This is my controller code:
vm.postUpdateITSM = function (itsm) {
$http({
method: "POST",
url: "api/sources/" + itsm.Id,
data: {
id: itsm.Id,
dto: {
ConnectorType: itsm.Type,
SourceName: itsm.ServerName,
DisplayName: itsm.DisplayName,
Credentials: JSON.stringify(itsm.UserName,
itsm.Password),
Url: itsm.URL,
Settings: JSON.stringify(itsm.ResolveAlerts ? itsm.ResolveAlerts : false,
itsm.AcknowledgeAlerts ? itsm.AcknowledgeAlerts : false,
itsm.SyncInterval,
itsm.IncidentInterval,
itsm.Status ? itsm.Status : "")
}
}
});
}
And on the back end: The dto is always null when called.
public async Task<IHttpActionResult> Update(int id, [FromBody] SourceDto dto)
{
var source = Mapper.Map<Source>(dto);
source.SourceID = id;
source.ServerCount = "";
var res = await SystemActors.SourceManager.Ask(new UpdateSource(source));
var failure = res as Status.Failure;
if (failure != null)
{
return InternalServerError();
}
var success = ((SqlResult<object>) res).Success;
if (!success)
{
return Content(HttpStatusCode.BadRequest, "Failed to update source.");
}
return Ok(new ResponsePackage {Success = true});
}
And this is the SourceDto class:
public class SourceDto
{
public string ConnectorType { get; set; }
public string SourceName { get; set; }
public string DisplayName { get; set; }
public string Credentials { get; set; }
public string Url { get; set; }
public string Settings { get; set; }
}
Your frontend data is formatted a bit wrong - the data parameter should just be the one object your ASP.NET controller is expecting in the [FromBody], your SourceDto model - and the id should be a query string:
method: "POST",
url: "api/sources/" + itsm.Id,
data: {
ConnectorType: itsm.Type,
SourceName: itsm.ServerName,
DisplayName: itsm.DisplayName,
Credentials: JSON.stringify(itsm.UserName,
itsm.Password),
Url: itsm.URL,
Settings: JSON.stringify(itsm.ResolveAlerts ? itsm.ResolveAlerts : false,
itsm.AcknowledgeAlerts ? itsm.AcknowledgeAlerts : false,
itsm.SyncInterval,
itsm.IncidentInterval,
itsm.Status ? itsm.Status : "")
}
});
ASP.NET will apply the request body to the expected model - if it doesn't match, you'll get null

append an array to 'formdata' and how to get server side?

I'm using FormData to upload files. I also want to send an array of other data.
When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'ProIList' array below, everything else works fine but no array is sent
this is my angular.js file code :
this.AddPro = function (file, P) {
var formData = new FormData();
formData.append("file", file);
formData.append("name", P.name);
formData.append("description", P.description);
formData.append("ProIList", P.ProIList); // this is array list
var Response = $http.post("/Product/AddProduct", formData,
{
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function (res) {
Response = res;
})
.error(function () {
});
return Response;
}
this is my controller method :
[HttpPost]
[Route("AddProduct")]
public string AddProduct(string name, string description, IList<ProductItems> ProIList) // here i m not getting array
{
Products objP = new Products();
string Res = "";
objP.name = name;
objP.description = description;
db.Promotions.Add(objP); // and here add product is done now want to add ProductItems table entry so how can do
db.SaveChanges();
return Res;
}
this is my entity productItmes :
[Table("ProductItems ")]
public class ProductItems
{
[Key]
public int id { get; set; }
[ForeignKey("Products")]
public int pid {get; set;}
public int Qty { get; set; }
public Decimal Rate { get; set; }
public virtual Products Products { get; set; }
}

Resources