I'm trying make an application with Ionic framework which can take and send data to MS SQL server. For this I am using web api. I have no problem with taking data but something wrong with send new datas. Here is my ionic code :
angular.module('starter.controllers',[])
.controller('CheckListCtrl', function($scope, ChecklistService, $ionicPopup) {
function addCheck(){
ChecklistService.addCheck()
}
.factory('ChecklistService', ['$http', function ($scope, $http) {
var urlBase = 'http://localhost:56401/api';
var CityService = {};
CityService.addCheck = function(){
var url = urlBase + "/TBLCHECKLISTs"
var checkdata = {
AKTIF : true,
SIL : false,
KAYITTARIHI : Date.now(),
KULLANICIID : 3,
BASLIK : "Onur",
TAMAMLANDI : false,
TAMAMLANMATARIHI : null,
GUN : 1
}
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: checkdata
});
return request;
}
return CityService;
}]);
And here is my web api:
[HttpPost]
[ResponseType(typeof(TBLCHECKLIST))]
public IHttpActionResult PostTBLCHECKLIST(TBLCHECKLIST tBLCHECKLIST)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
tBLCHECKLIST.KAYITTARIHI = DateTime.Now;
db.TBLCHECKLISTs.Add(tBLCHECKLIST);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = tBLCHECKLIST.TABLEID }, tBLCHECKLIST);
}
When i try to send i get this exception:
After, I realize that I take that exception because my checkdata is never come to web api. I don't know why.
These are not the datas I send:
I have tried different versions of post request but nothing. When I try to send data with PostMan, it works and I can insert data to my database. But why I can't do it with my application? Can anybody help me?
I think this should be the problem:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
Try this:
return $http.post(url, checkdata);
And in your API:
[HttpPost]
[ResponseType(typeof(TBLCHECKLIST))]
public IHttpActionResult PostTBLCHECKLIST([FromBody]TBLCHECKLIST tBLCHECKLIST)
{
//code here
}
Also, make sure your checkdata properties match the ones in your TBLCHECKLIST c# type.
Related
We use a rest api to get customer information. A lot of the GET request were already written by others. I was able to follow their code to create other GET request, but one of the API methods for updating a customer requires using json patch. Below I have pasted in sample code of a current GET method, a Patch method (that I don't know how to implement) and a sample function written in javascript on how to use the json-patch that came from the api creators demo documentation:
public GetCustomerResponse GetCustomerInfo(CustomerRequest request)
{
//All of this works fine the base url and token info is handled elsewhere
var restRequest = CreateRestRequest($"customer/account?id={request.id}", RestSharp.Method.GET);
var response = CreateRestClient().Execute<GetCustomerResponse>(restRequest);
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Data;
}
else
{
return new GetCustomerResponse(response.Content);
}
}
public EditCustomerResponse EditCustomer(EditCustomerRequest request)
{
var restRequest = CreateRestRequest($"customer/account?id={request.id}", RestSharp.Method.PATCH);
var response = CreateRestClient().Execute<EditCustomerResponse>(restRequest);
//how do I pass along json patch data in here???
//sample json might be like:
//[{'op':'replace','path':'/FirstName','value':'John'},{'op':'replace','path':'/LastName','value':'Doe'}]
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Data;
}
else
{
return new EditCustomerResponse(response.Content);
}
}
//javascript demo version that is working
function patchCustomer(acctId, patch, callback) {
var token = GetToken();
$.ajax({
method: 'PATCH',
url: BaseURI + 'customer/account?id=' + acctId,
data: JSON.stringify(patch),
timeout: 50000,
contentType: 'application/json; charset=UTF-8',
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + token.access_token) },
}).done(function (data) {
if (typeof callback === 'function')
callback.call(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Request failed: " + textStatus);
console.error(errorThrown);
failureDisplay(jqXHR);
});
}
This was pretty simple. After viewing similar questions on stackoverflow, I initially was trying something like this:
var body = new
{
op = "replace",
path = "/FirstName",
value = "John"
};
restRequest.AddParameter("application/json-patch+json", body, ParameterType.RequestBody);
It would not work. To get it to work, I added a patchparameters class with op, path and value properties, and then added a list property of type patchparameters to my EditCustomerRequest class and used it like this:
restRequest.AddJsonBody(request.patchParams);
I'll be glad to get your help. I'm using AngularJS version 1.6.5 and trying to use http delete method. On server side i'm using asp.net MVC5 Web API.
When i'm trying to delete a record i'm getting error 405 (Method Not Allowed).
This is my AngularJS code:
$scope.Delete = function (CustomerNumber) {
$http.defaults.headers["delete"] = {
'Content-Type': 'application/json,charset=utf-8'
};
$http({
method: "DELETE",
url: "/Api/Customer/" + CustomerNumber
}).then(function successCallback(response) {
$scope.Customers = response.data;
$scope.addCustomer.$setPristine();
$scope.addCustomer.$setUntouched();
$scope.Customer = {};
$scope.error = "";
}, function errorCallback(response) {
$scope.error = "Error on delete customer (" + response.status + ") - " + response.statusText;
});
};
and this is my asp.net code:
public List<Customer> Delete(string CustomerNumber)
{
DataLayer dal = new DataLayer();
CustomerViewModel cvm = new CustomerViewModel();
Customer cust = (from x in dal.Customers where x.CustomerNumber == CustomerNumber select x).ToList<Customer>()[1];
dal.Customers.Remove(cust);
dal.SaveChanges();
cvm.customers = dal.Customers.ToList<Customer>();
return cvm.customers;
}
I tried many ways and none of them worked. I would like to get your help.
Thank you.
Use JSON.stringify
$http({
method: "DELETE",
url: "/Api/Customer/" + JSON.stringify(CustomerNumber)
})
I have built a RESTful web service using ASP.NET HttpHandler, when running the web service project im redirected to the default page from which I can choose to download the DOJO code for my Client app.
here is a code snippet from the downloaded file:
function PickrWebService(){ self = this; }
PickrWebService.prototype = {
self: null,
urlString: "http://AYMAN/Handler.ashx",
CreateUser:function(Email,Username,Password,FirstName,Surname,Birth,Gender,Mobile,Picture,Address,successFunction,failFunction,token) {
var data = { 'interface': 'PickrWebService', 'method': 'CreateUser', 'parameters': {'Email':Email,'Username':Username,'Password':Password,'FirstName':FirstName,'Surname':Surname,'Birth':Birth,'Gender':Gender,'Mobile':Mobile,'Picture':Picture,'Address':Address}, 'token': token };
var jsonData = dojo.toJson(data);
var xhrArgs = {
url: self.urlString,
handleAs: 'json',
postData: jsonData,
load: successFunction,
error: failFunction };
var deferred = dojo.xhrPost(xhrArgs);
},
CheckUserExistence:function(Email,successFunction,failFunction,token) {
var data = { 'interface': 'PickrWebService', 'method': 'CheckUserExistence', 'parameters': {'Email':Email}, 'token': token };
var jsonData = dojo.toJson(data);
var xhrArgs = {
url: self.urlString,
handleAs: 'json',
postData: jsonData,
load: successFunction,
error: failFunction };
var deferred = dojo.xhrPost(xhrArgs);
}
}
I need help on how to use this code in my client app, and what does the parameter 'token' refer to?
The code is a javascript object for you service which you can call the webservice, by invoking the methods. token is not the part of dojo.xhrPost, it might be from the ASP.Net for passing authentication token. If you have not setup the security on the service, you could ignore it.
var successFunction = function(args){
//Handle the success response.
}
var failFunction= function(err){
//Handle the failure response.
}
var service = new PickrWebService();
service.createUser(Email,Username,Password,
FirstName,Surname,Birth,Gender,Mobile,Picture,Address,successFunction,failFunction);
Apart from the above code, you need to add the dojo api in you client.
I am trying to post data and return some content posting to a .net web api using angularjs
here is my web api
[HttpPost]
public HttpResponseMessage Post()
{
return new HttpResponseMessage()
{
Content = new StringContent(
"<strong>test</strong>",
Encoding.UTF8,
"text/html"
)
};
}
and here is my post from my client
$http({
url: 'my happy url',
method: "POST",
data: objData,
headers: {
'Content-Type': 'text/html'
}
}).success(function (data, status, headers, config) {
console.log(headers());
}).error(function (data, status, headers, config) {
console.log("error");
});
my problem is I do not get any data returned. I am sure I am missing something simple. Thanks for your help.
in the above code the data parameter is empty and I would expect to find the string "test" in the data parameter.
Instead of HttpResponseMessage, can you try to use IHttpActionResult? Sample code as below.
public IHttpActionResult PostSample()
{
return Content(HttpStatusCode.OK, "Test String");
}
I have an angular application, and I am trying to get a list of users from the server. I ran into an issue. I have page call CurrentUsers. If CurrentUsers method returns a Json Object, the entire object is display on the page regardless of what I do in the app controller and html page. If the method return a view, it does not display anything. However, I can hard code the json object in the cotroller, and it will work fine.
As a result, I created another method to return the json object. I made a call to that method, but it never reached the server. Your help will be very much appreciated.
The CurrentUsers Method returning a JSON Object, the entire json object display on the screen regardless
[HttpGet]
public JsonResult CurrentUsers()
{
List<Users> currentUser = new List<Users>()
{
new Users{ UserName = "JDoe", Professor="SSmith", Course = "English1"},
new Users{ UserName = "ADan", Professor="SDhor", Course = "Science"},
new Users{ UserName = "ADes", Professor="SCarry", Course = "Religion101"},
new Users{ UserName = "DJay", Professor="SCrowe", Course = "Teaching101"},
new Users{ UserName = "MAnne", Professor="TRow", Course = "PreCalc"},
};
return Json(new { Ok = true, data= currentUser });
// return View();
}
If the above method return a View, I can modify the controller as
shown below, and I will see the appropriate Information
Registration.controller('CurrentUsersController', function ($scope, $http) {
$scope.currentUsers = [{ "Professor": "SSmith", "UserName": "JDoe", "Course": "English1" }, { "Professor": "SDhor", "UserName": "ADan", "Course": "Science" }, { "Professor": "SCarry", "UserName": "ADes", "Course": "Religion101" }]
});
I modified the controller to use a service and created the method below to read the Current Users so that the view can simply return a View(). However, I have not been able to get the 'GET'to work.
[HttpGet]
public JsonResult GetUsers()
{
List<Users> currentUser = new List<Users>()
{
new Users{ UserName = "JDoe", Professor="SSmith", Course = "English1"},
new Users{ UserName = "ADan", Professor="SDhor", Course = "Science"},
new Users{ UserName = "ADes", Professor="SCarry", Course = "Religion101"},
new Users{ UserName = "DJay", Professor="SCrowe", Course = "Teaching101"},
new Users{ UserName = "MAnne", Professor="TRow", Course = "PreCalc"},
};
return Json(new { Ok = true, data = currentUser , message =
"Success"}, JsonRequestBehavior.AllowGet);
}
the modify CurrentUsers Method to return a view
public ActionResult CurrentUsers()
{
return View();
}
My modify controller
Registration.controller('CurrentUsersController', function ($scope, GetUSerService) {
$scope.message = 'this is the Current User controller';
$scope.currentUsers = [];
var result = GetUSerService.getData()
.then(function (result) {
console.log('the result');
console.log(result.data);
});
});
my service
Registration.service('GetUSerService', function ($http,$q) {
this.getData = function () {
var deferredObject = $q.defer();
$http.get('/Home/GetUsers').
success(function (data) {
console.log('service call data');
console.log(data);
deferredObject.resolve({ success: true, data : data.data });
}).
error(function () {
deferredObject.resolve({ success: false, data : '' });
});
return deferredObject.promise;
};
});
Updated 10/6 #5:50
#FernandoPinheiro answer works for me. The only thing is that the GetUsers action is being called twice.
Updated 10/7
I figured out why the post was being done twice. On my template, I had ng-app="Registration", and I had ng-controller= "CurrentUsersController". Because I specified the controller name in the route provider, I did not need it to add it to the partial view. As soon as I removed it from the view, it worked as expected.
Your GetUserService is calling $http.post('/Home/GetUsers') instead of $http.get('/Home/GetUsers').
Besides, shouldnt you set the Route attribute for the action ?