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
Related
I am passing a json data using jQuery to a Ajax call. I want to read this json in my Application_BeginRequest function on global.ascx for some puspose.
Where can i find this data in "Request" object.
I found that the Questystring and the Form of Request object. both are empty.
Calling ajax function as below using jQuery
Regards
Umesh
var inputData = "{'ID':'" + ID + "', 'Code':'" + Centre +"'}";
var pageURL = window.location.protocol + "//" + window.location.host +
"/webmethod.aspx/MyFunction"
$.ajax({
type: "POST",
url: pageURL,
data: inputData,
contentType: "application/json; charset=utf-8",
dataType: "json",
P.S - Assuming you want to post the json data using **jquery** to your ASPX page, Adding a sample below.
function GetEmployee()
{
var jsonObj = {"Org":0 ,"Dept":0,"Desg":0,"Grp":0,"SubGrp":0,"Loc":0,"Prv":'CanViewEmployee',"CustAttrId":0,CustAttrVal:"","Status":'1' };
$.ajax({
url: 'EmployeeSearchControl.aspx/populateJsonResult',
datatype: 'json',
data:JSON.stringify(jsonObj),
method: 'Post',
success: function (data) {
if(data != null || data != "")
{
for(var i=0;i<data.length;i++)
{
addEmployeeToGrid(data[i]);
}
}
}
})
}
public class JSONRequest
{
public long Org { get; set; }
public long Dept { get; set; }
public long Desg{ get; set; }
public long Grp { get; set; }
public long SubGrp { get; set; }
public long Loc { get; set; }
public long Cat { get; set; }
public string Prv { get; set; }
public long CustAttrId { get; set; }
public string CustAttrVal { get; set; }
public string Status { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
string ap = Request["org"];
HttpContext.Current.Request.InputStream.Position = 0;
string jsonString = "";
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest masterDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<JSONRequest>(jsonString);
}
Hope it helps. Please let me know if you require any other help.
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
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
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);
});
How can I post a list from view to controller using ajax? I have this code in client side:
$(".js-save").click(function (e) {
e.preventDefault();
var button = $(this);
var lstERegistroVenta = [];
var ERegistroVenta = new Object();
ERegistroVenta.IdProducto = 1;
ERegistroVenta.IdInventario = 2;
ERegistroVenta.MontoProducto = 12.5;
ERegistroVenta.CantidadProducto = 1;
ERegistroVenta.MontoTotalSinIGV = 20.5
ERegistroVenta.MontoTotal = 23.5
lstERegistroVenta.push(ERegistroVenta);
$.ajax({
dataType: 'json',
type: 'POST',
url: "/API/Inventario/Venta/1",
data: JSON.stringify({ lstERegistroVenta: lstERegistroVenta }),
success: function () {
toastr.success("Correcto");
},
error: function () {
toastr.error("Error");
}
});
});
When I try to pass the data I receive only empty list. In server side I have this API
[HttpPost]
[Route("API/Inventario/{Venta}/{IdProducto}")]
public IHttpActionResult AsignarProducto(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
return Ok();
}
public class ERegistroVenta
{
public int IdProducto { get; set; }
public int IdInventario { get; set; }
public double MontoProducto { get; set; }
public int CantidadProducto { get; set; }
public double MontoTotalSinIGV { get; set; }
public double MontoTotal { get; set; }
}
First of all, I wouldn't suggest calling an API method directly from a View. Instead, call a controller method which should internally call the API method. The code for this would look something like below.
$.ajax({
dataType: 'json',
type: 'POST',
url: "/TestController/TestMethod",
data: { "IdProducto" : "1", "lstERegistroVenta": lstERegistroVenta },
success: function () {
toastr.success("Correcto");
},
error: function () {
toastr.error("Error");
}
});
[HttpPost]
public void TestMethod(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
// Your Logic Here
}
I found a solution. Maybe my mistake was that I didn't send an anonymous list of objects.
Take a look to this:https://kwilson.io/blog/post-an-array-of-objects-to-webapi-using-jquery/
My solution below:
$(".js-save").click(function (e) {
e.preventDefault();
var button = $(this);
var lstERegistroVenta = [];
var ERegistroVenta = new Object();
ERegistroVenta.IdProducto = 1;
ERegistroVenta.IdInventario = 2;
ERegistroVenta.MontoProducto = 12.5;
ERegistroVenta.CantidadProducto = 1;
ERegistroVenta.MontoTotalSinIGV = 20.5
ERegistroVenta.MontoTotal = 23.5
lstERegistroVenta.push(ERegistroVenta);
$.ajax({
dataType: 'json',
method: 'POST',
url: "/API/Inventario/Venta/1",
data: { '': lstERegistroVenta },
success: function () {
toastr.success("Correcto");
},
error: function () {
toastr.error("Error");
}
});
});
And in server side:
[HttpPost]
[Route("API/Inventario/{Venta}/{IdProducto}")]
public IHttpActionResult AsignarProducto(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
// Logic Here
}
Hope this helps to another user.