I am new to angular and ionic, so I started creating simple ionic application with AngularJS but I am facing a problem, I tried searching it on google but could not figure it out.
for testing I hard-corded parameters in angular controller.
after click on submit button from ionic app, it hitting to the relevant action in API controller but data showing as null,
if anyone can help to figure this out it will be appreciate,
AngularJs Controller
$scope.savenewdansal= function(newDansal){
$http({
method : 'POST',
url : 'http://localhost:51079/api/Dansal/SaveNewDansal',
dataType: 'json',
data: JSON.stringify({"MainCategory": "category1","SubCategory": "subCateMy","District": "Central","City": "Colo","date": "2000-01-01T00:00:00","Time": "2001-01-01T00:00:00","Venue": "kurudnwa","contacts": "nocon"}),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
console.log(data.errors.name)
} else {
console.log(data.message);
}
});
WebAPI Action
[HttpPost]
[ActionName("SaveNewDansal")]
public VM_NewDansal SaveDansal(VM_NewDansal newDansal)
{
return newDansal;
}
Model Class
public class VM_NewDansal
{
public string MainCategory { get; set; }
public string SubCategory { get; set; }
public string District { get; set; }
public string City { get; set; }
public string date { get; set; }
public string Time { get; set; }
public string Venue { get; set; }
public string contacts { get; set; }
}
both Ionic App and WebAPI Service running on localhost
Thank you
After searching through some another post from google, i find out a solutions for my problem, thanks for everyone who tried to help me.
first I change
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
to
headers : {'Content-Type': 'application/json'}
then it gave me following error,
XMLHttpRequest cannot load http://localhost:51079/... Response for preflight has invalid HTTP status code 405
so figure it out that error occurred because it a Cross-Origin need to enable because my ionic app and webserice both run in local host insame machine but in diffrent ports.
so if anyone want to enable CORS check follow link
link
otherwise check it in Internet Explorer,it does not consider the port when comparing origins.
thanks
Related
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
How to pass list of object from Angular to a Web API ?
I tried it using content-type as application/json but it shows CORS preflight error.
Following is the Web API Post Method :
[HttpPost]
public bool getDetails(List<Subnets> data)
{
//Logic here
}
Following is the angular code :
$scope.save = function (jsondata) {
$http({
method: "POST",
url: "http://localhost:60262/api/IPUpload/getDetails",
data: jsondata,
headers: {
'Content-Type': 'application/json'
}
}).then(function (data) {
alert('success');
if (data.status) {
$scope.msg = "Data has been inserted ! ";
}
else {
$scope.msg = "Error : Something Wrong";
}
}, function (error) {
alert('fail');
$scope.msg = "Error : Something Wrong";
})
}
Following is the Subnet class :
public class Subnets
{
public string ID { get; set; }
public string Subnet { get; set; }
public string IPAddress { get; set; }
public string ServerName { get; set; }
public string Mac { get; set; }
public string Vmware { get; set; }
public string Usage { get; set; }
public string Owner { get; set; }
public DateTime ExpiryDate { get; set; }
public string Email { get; set; }
public string SwitchIP { get; set; }
public string SwitchPort { get; set; }
public string PortVLAN { get; set; }
public string Zone { get; set; }
public string Justification { get; set; }
public string CustomerID { get; set; }
public string Remarks { get; set; }
}
I tried using content-type as ' application/x-www-form-urlencoded; charset=UTF-8'. It calls the API action method but the parameter "data" is empty. With content-type as 'application/json', it shows CORS preflight error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://localhost:60262/api/StaticIPUpload/getDetails. (Reason: CORS
header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).
Thanks in advance.
Solution :
I added following piece of code in global.asax and it worked :
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
CORS does not allow application/json . You were okay with text/plain
You can even avoid the headers part for now. As you said It calls the API action method but data is empty. Probably jsondata is not a valid object.
Try with the following code.
$http({
method: "POST",
url: "http://localhost:60262/api/IPUpload/getDetails",
data: JSON.stringify(jsondata)
}).then(function (data) {
public bool getDetails(List<Subnets> data)
{
}
without the[HttpPost].
I would also like to see your Subnets Class and jsondata
If I remember correctly, Angular.js triggers the preflight request when you use application/json. Your web API needs to respond to the preflight request with a 200 response.
If you are writing your own API, make sure that OPTION is enabled in the web API on the http://localhost:60262/api/IPUpload/getDetails endpoint.
After you enable the OPTION HTTP method and return the 200 Angular should work as expected.
You need to enable CORS on web API front. By default angularjs supports cross domain ajax calls. But if server doesn’t allow cross domain calls it will fail.
You can enable CORS as follow:
Enable options calls on server side.
For each actual post end point you need an options end point as well, so that when browser checks CORS and send a option call it should return 200.
Also application\json is supported in cross domain ajax calls.
I am making a POST request from Angular to Web API 2:
let params = {
ReportName: reportName,
ParamName: paramName,
ParamValues: paramValues
};
this.$http.post("/reportsweb/api/reports/", params).then(response => {
deferred.resolve(response.data);
}, response => {
deferred.reject(response);
})
Web API method is defined like this:
[HttpPost]
[ResponseType(typeof(Dictionary<string, string>))]
public IHttpActionResult GetDependentParameterValues([FromBody]ArgumentModel args)
{
// args here is null for some reason
}
where ArgumentModel is defined the same way as params var in Angular:
public class ArgumentModel
{
public string ReportName { get; set; }
public string ParamName { get; set; }
public string ParamValues { get; set; }
}
However, when I hit a breakpoint in WebAPI method, I see that args = null :(
Any idea why?
Thanks.
Here is the screenshot from angular app:
[HttpPost, Route("api/EtiketAPI/EtiketEkle/{makaleId}")]
public HttpResponseMessage EtiketEkle(string makaleId,Etiket[] values)
I have been recently using web api. I am stuck to bind an array which comes from web request and the request method is post method. Is there any way to bind data comes from request to my specified object ?
I am sending data with angularjs. Here is data form
[{"EtiketId":1,"EtiketAdi":"Microsoft","EtiketRadi":"microsoft","Makaleler":null},{"EtiketId":2,"EtiketAdi":".net","EtiketRadi":"-net","Makaleler":null}]
and my class
public class Etiket
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EtiketId { get; set; }
public string EtiketAdi { get; set; }
public string EtiketRadi { get; set; }
public virtual ICollection<Makale> Makaleler { get; set; }
}
here are you answers :
Sending binary data along with a REST API request
Processing binary data in Web API from a POST or PUT REST request