I have a class
public class Customer
{
private int _Id;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
private String _Name;
public String Name
{
get { return _Name; }
set { _Name = value; }
}
private String _Address;
public String Address
{
get { return _Address; }
set { _Address = value; }
}
}
I need to save data using this class. I need to know how to call this class in data function
$scope.Save = function () {
var httpreq = {
method: 'POST',
url: 'ajs.aspx/Save',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'dataType': 'json'
},
data: { //** Here How to call assign object value for my customer class **// }
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
How to create class object and assign value for my customer class in this data section.
In my web method
[System.Web.Services.WebMethod()]
public static void Save(Customer objcsr)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "insert into customer (Name, Address) values (#Name, #Address);";
cmd.Parameters.AddWithValue("#Name", objcsr.Name);
cmd.Parameters.AddWithValue("#Address", objcsr.Address);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
You need pass the json format data with the class properties, Try this below code
Var objcsr={Id:"1",Name:"Donald Trump",Address:"Alien Planet"}
$scope.Save = function () {
var httpreq = {
method: 'POST',
url: 'ajs.aspx/Save',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'dataType': 'json'
},
data: objcsr
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
When you are sending data from client to server, according to the best practices, the data should be sent either in the form of XML or JSON.
Hence, the JSON of your class object could be something like
var obj = {
"id" : "YOUR ID",
"name" : "YOUR NAME",
"address" : "YOUR ADDRESS"
}
Moreover, according to the best practices, the http requests should be made using a factory or service.
So your factory should be something like
angular.module("YOUR_MODULE").factory('YOUR_SERVICE',function($http,$q){
var obj = {};
obj.saveObject = function(data){
var defer = $q.defer();
$http.post("YOUR URL",data).then(function(response){
defer.resolve(response);
},function(error){
defer.reject(error);
});
return defer.promise;
}
return obj;
});
And thus you can make a controller call as
$scope.Save = function (data) {
YOUR_SERVICE.saveObject(data);
}
and that can be called like
var obj = {
"id" : "YOUR ID",
"name" : "YOUR NAME",
"address" : "YOUR ADDRESS"
}
$scope.Save(obj);
If your getting it from form elements then you should be using it like
$scope.Save = function () {
var customerObject={
"Id": $scope.customerId,
"Name": $scope.customerName,
"Address":$scope.customerAddress
};
var httpreq = {
method: 'POST',
url: 'ajs.aspx/Save',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
data: { customerObject }
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
Also Note that, the objectName and their respective properties that your are passing should match with that of the objectName in webmethod. For example
Your properties are
your corresponding json object must have the same properties
Id: $scope.Id
Name: $scope.Name
Address: $scope.Address
Related
Using angularjs 1.3 and C# .net core web api
I have a ng-file-upload which being used to upload file. When the upload method is called I want to pass in an extra array of some data to the upload method which is then received by the method at my web api. Here is my ng-file-upload
factory.upload = function (file, myArray) {
var url = '{0}upload'.format(apiPath)
return Upload.upload({
url: url,
arrayKey: '',
data: { file: file, myArray: myArray}
}).then(function (res) {
return res;
});
};
Below is my webapi:
[HttpPost("upload")]
public async Task<IActionResult> FileUpload(IFormFile file, List<string> myArray)
{
//code
}
And finally here is the array which I am trying to pass along with upload to my webapi:
[
{
id: "1",
name: "steve"
},
{
id: "2",
name: "adam"
}
]
The issue is in my webapi, the myArray parameter which is to accept the array from the UI is always null. I searched online and its mentioned to add
arrayKey: ''
But still doesnt works. Any inputs?
---Updated---
I created a string array as :
var cars = ["steve", "adam", "ronnie"];
And updated my api as:
List<ArrayItem> myArray
The above code works. So looks like there is issue with array being passed.
I am passing the following array by creating like this:
var myArray= [];
for (var i = 0; i < myJson.length; i++) {
myArray.push({
id: myJson[i].id,
name: myJson[i].name,
});
}
The result of above as seen in console:
Array(2)
0:{id: "1", name: "steve"}
1:{id: "2", name: "adam"}
Whats missing here?
For passing object array, you need to define the list object to accept the parameters.
ArrayItem with Id/Name properties.
public class ArrayItem
{
public int Id { get; set; }
public string Name { get; set; }
}
Change action
public async Task<IActionResult> FileUpload(IFormFile file, List<ArrayItem> myArray)
{
return Ok();
}
Update
You need to remove arrayKey: '[]', try code below:
app.service('crudService', function ($http, Upload) {
var baseUrl = 'http://localhost:50829';
this.uploadFile = function (file, array) {
return Upload.upload({
url: baseUrl + "/api/books/file/upload",
//arrayKey: '[]',
data: { file: file, array: array },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (res) {
return res;
}, function (err) {
throw err;
});
};
});
I am trying to access REST web service from angularjs. I am not able to call it successfully.
AngularJs Code
var singleOrderUrl = "/singleOrder/retrieve";
function getSingleOrderDetails(userName,singleOrderUrl,$http,$q) {
var fd = new FormData();
var deffered = $q.defer();
fd.append('USERNAME', 'test123');
//fd.append();
//fd.append();
console.log("inside service"+userName+"singleOrderUrl:::"+singleOrderUrl);
return $http.get(singleOrderUrl, fd, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined,
}
}).success(function(response) {
console.log(response);
responseData = response.data.toString();;
deffered.resolve(response);
return responseData;
}).error(function(error) {
alert("error");
deffered.reject(error);
return "failed";
});
};
Rest Service code
#RestController
public class SingleOrderHistoryController {
private static final Logger logger = LoggerFactory.getLogger(SingleOrderHistoryController.class.getName());
#RequestMapping(value = "/singleOrder/retrieve", method=RequestMethod.GET, produces="application/json")
public List<SingleHistoryRecord> getSingleOrderDetails(#RequestParam(value = Constants.USER_NAME, required = true) String userName, HttpServletRequest request,HttpServletResponse response) throws Exception {
logger.debug("inside SingleOrderHistoryController ");
List<SingleHistoryRecord> singleOrderHistoryList = new ArrayList<SingleHistoryRecord>();
SingleHistoryRecord record1 = new SingleHistoryRecord();
SingleHistoryRecord record2 = new SingleHistoryRecord();
record1.setClientIdentifier(userName);
record1.setSubmitDate("01/05/2017");
record1.setStatus("Complete");
record1.setReferenceID("1234555");
record1.setOrderID("test123");
record2.setClientIdentifier(userName);
record2.setSubmitDate("01/05/2017");
record2.setStatus("Complete");
record2.setReferenceID("1234555");
record2.setOrderID("test123");
singleOrderHistoryList.add(record1);
singleOrderHistoryList.add(record2);
return singleOrderHistoryList;
}
Can anyone please advise what I am doing wrong here, It is getting the source code of the page in response instead of getting the list.
Hi I'm a newbie in web development and I'm having some trouble in inserting new data in my database.
First, there's an error in dbcontext.Tbl_Articles.Add(adto);
It says, cannot convert WebAPI.Models.Articles to WebAPI.DataLayer.Tbl_Articles
Another thing is, whenever I run my Web API, it says something like this - {"Message":"The requested resource does not support http method 'GET'."}
script file:
$scope.AddArticle = function ()
{
var data =
{
Category: $scope.Category,
IsCarousel: $scope.IsCarousel,
IsImportant: $scope.IsImportant,
HeaderImage: $scope.HeaderImage,
Title: $scope.Title,
ByLine: $scope.ByLine,
Content: $scope.Content,
Author: $scope.Author,
PublishStartDate: $scope.PublishStartDate_date + " " + $scope.PublishStartDate_time + $scope.PublishStartDate_time_ext,
PublishEndDate: $scope.PublishEndDate_date + " " + $scope.PublishEndDate_time + $scope.PublishEndDate_time_ext
};
$http(
{
method: 'POST',
url: 'http://project-aphrodite-uat-service.azurewebsites.net/api/articles/createarticle',
data: JSON.stringify(data)
})
.then(function successCallback(response)
{
console.log(response);
},
function errorCallback(response)
{
console.log("error" + response);
});
};
ArticlesController.cs:
[HttpPost]
[Route("api/articles/createarticle")]
public Articles CreateArticle(Articles obj)
{
DataLayer.DataLayer dl = new DataLayer.DataLayer();
dl.CreateArticle(obj);
return obj;
}
DataLayer.cs:
public string CreateArticle(Articles obj)
{
var adto = new Articles();
adto.Category = obj.Category;
adto.IsCarousel = obj.IsCarousel;
adto.IsImportant = obj.IsImportant;
adto.HeaderImage = obj.HeaderImage;
adto.Title = obj.Title;
adto.ByLine = obj.ByLine;
adto.Content = obj.Content;
adto.Author = obj.Author;
adto.PublishStartDate = obj.PublishStartDate;
adto.PublishEndDate = obj.PublishEndDate;
using (ArticleEntities dbcontext = new ArticleEntities())
{
dbcontext.Tbl_Articles.Add(adto);
dbcontext.SaveChanges();
return "test";
}
}
I hope someone could help me fix these. Thankie so much!
function viewReports(firstDate, lastDate) {
var selected = $('#ReportSelected').find(":selected");
var controller = "PortalReports";
var method = "GetReport";
var urlAjax = $("#basePath").val() + controller + "/" + method;
var companydropdown = $('#ReportSelected :selected').data("companydropdown");
var agencydropdown = $('#ReportSelected :selected').data("agencydropdown");
var userdropdown = $('#ReportSelected :selected').data("userdropdown");
var data =
{
reportSelected: selected.text(),
firstDate: firstDate,
lastDate: lastDate,
companydropdown: companydropdown,
agencydropdown: agencydropdown,
userdropdown: userdropdown
};
/*var data =
[{
"reportSelected": selected.text(),
"firstDate": firstDate,
"lastDate": lastDate,
"companydropdown": companydropdown,
"agencydropdown": agencydropdown,
"userdropdown": userdropdown
}];*/
var answer = JSON.stringify({ data });
$.ajax({
traditional: true,
data: JSON.stringify({ data }),
url: urlAjax,
success: function (response) {
loadReport(response);
},
error: function (ob, errStr) {
alert("An error occured. Please try again.");
}
});
//Mvc
public JsonResult GetReport(JArray data)
{
var persons = data.Select(x => x.ToObject<InputJson>());
JArray data is always null irrespective of how many ways I add square brackets of remove quotation marks etc, what am I doing wrong!!!
Prefer simple Object returned in array for readability as I might need to add to it.
Since you are sending a complex data structure(array), you should specify the contentType property when making ajax call. Specify the value of contentType property as "application/json"
//Values hard coded, you may replace with real values from your form.
var dataArray = [{
reportSelected:'201501',
firstDate: '11/12/2010',
lastDate: '12/12/2010',
companydropdown: 4,
agencydropdown: 6,
userdropdown: 16,
}];
var urlAjax = "/Home/GetReport"; // Hard coded for demo. Read further..
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(dataArray),
url: urlAjax,
success: function (response) {
console.log(response);
},
error: function (ob, errStr) {
alert("An error occured. Please try again.");
}
});
I suggest you create a view model /DTO to represent the data you are sending and use that in your action method.
public class ReportRequest
{
public string reportSelected { get; set; }
public DateTime firstDate { get; set; }
public int companydropdown { get; set; }
}
[HttpPost]
public JsonResult GetReport(IEnumerable<ReportRequest> data)
{
//do something with data
// to do : Return something
}
In the example, I hardcoded the value of urlAjax variable. You may consider using the html helper methods to generate the correct relative url path to the action method(s) as explained in this post.
In my Angular/WebAPI app I'm struggling with retrieving a specific record by its id.
On the Front-End I have a controller and a data service. The controller calls a method on the data service, and the data service makes $http call to a WebAPI.
In my controller I'm passing the OID of the desired record to the getServiceRequestById method of the data service. Once of my issues is, that the actual value of that OID comes out as :1 instead of just 1.
My other issue is, that when the data service makes a call to WebAPI, the WebAPI perceives the request, as if it caries no ID in it, and passes that request onto its Get() method, instead of Get(int Id).
Here is my Front-End controller:
angular.module('frontEndApp').controller('EditServiceRequestCtrl',['$scope', 'requestsRepository','$routeParams',
function ($scope, requestsRepository,$routeParams) {
console.log("This is EditServiceRequestCtrl ; $routeParams: " + $routeParams);
//First we make a call to the data service, to fetch our ServiceRequest by its OID
//Then, in the callback function, we populate the $scope models below with the data of our retreived ServiceRequest
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
var Id = getCleanId();
//var cleanId = id.substring(0, 2);
console.log('getCleanId Id: ' + Id);
requestsRepository.getServiceRequestById(Id, function (request) {
$scope.OID = request.OID;
$scope.RequestorName = request.RequestorName;
$scope.RequestorBusinessUnit = request.RequestorBusinessUnit;
$scope.CustomerName = request.CustomerName;
$scope.CscContactPerson = request.CscContactPerson;
$scope.IsWbsCodeAvailable = request.IsWbsCodeAvailable;
$scope.SalesforceIdNumber = request.SalesforceIdNumber;
$scope.ProjectCtv = request.ProjectCtv;
$scope.RequestedCompletionDate = request.RequestedCompletionDate;
$scope.ToBeUsedForCloudMigration = request.ToBeUsedForCloudMigration;
$scope.ToBeUsedForDatacenterMove = request.ToBeUsedForDatacenterMove;
$scope.ToBeUsedForServerRefresh = request.toBeUsedForServerRefresh;
$scope.DataRequirements = request.DataRequirements;
$scope.DataProtectionRequirements = request.DataProtectionRequirements;
$scope.ProjectedDataAvailability = request.ProjectedDataAvailability;
$scope.DiscoveryLeadName = request.DiscoveryLeadName;
$scope.SelectedCountries = request.SelectedCountries;
$scope.ManualDiscovery = request.ManualDiscovery;
$scope.AutomatedDiscovery = request.AutomatedDiscovery;
$scope.DataLoadUsingMasterTemplate = request.DataLoadUsingMasterTemplate;
$scope.DataLoadUsingAutomatedInterface = request.DataLoadUsingAutomatedInterface;
$scope.DataLoaderRequiresSitizenship = request.DataLoaderRequiresSitizenship;
$scope.countries = [
{
name: "US", checked: false
},
{
name: "UK", checked: false
},
{
name: "France", checked: false
},
{
name: "Germany", checked: false
},
{
name: "Sweden", checked: false
},
{
name: "Danmark", checked: false
}
];
var list = [];
$scope.checkit = function () {
for (var p in $scope.countries) {
if ($scope.countries[p].checked) {
list.push($scope.countries[p].name);
console.log("selected country: " + $scope.countries[p].name + " " + $scope.ProjectedDataAvailability);
}
} return list;
}
console.log('EditServiceRequestCtrl $scope.RequestorName : ' + $scope.RequestorName);
});
$scope.updateServiceRequest = function () {
var ServiceRequest = {
requestorName: $scope.RequestorName,
requestorBusinessUnit: $scope.RequestorBusinessUnit,
customerName: $scope.CustomerName,
cscContactPerson: $scope.CscContactPerson,
isWbsCodeAvailable: $scope.IsWbsCodeAvailable,
salesforceIdNumber: $scope.SalesforceIdNumber,
projectCtv: $scope.ProjectCtv,
requestedCompletionDate: $scope.RequestedCompletionDate,
projectedDataAvailability: $scope.ProjectedDataAvailability,
toBeUsedForCloudMigration: $scope.ToBeUsedForCloudMigration,
toBeUsedForDatacenterMove: $scope.ToBeUsedForDatacenterMove,
toBeUsedForServerRefresh: $scope.ToBeUsedForServerRefresh,
dataRequirements: $scope.DataRequirements,
dataProtectionRequirements: $scope.DataProtectionRequirements,
selectedCountries:
list.filter(function (itm, i, a) {
return i == a.indexOf(itm);
}).toString(),
projectedDataAvailability: $scope.ProjectedDataAvailability,
discoveryLeadName: $scope.DiscoveryLeadName,
manualDiscovery: $scope.ManualDiscovery,
automatedDiscovery: $scope.AutomatedDiscovery,
dataLoadUsingMasterTemplate: $scope.DataLoadUsingMasterTemplate,
dataLoadUsingAutomatedInterface: $scope.DataLoadUsingAutomatedInterface,
dataLoaderRequiresSitizenship: $scope.DataLoaderRequiresSitizenship
};
requestsRepository.updateServiceRequest(ServiceRequest);
}
}]);
Here is my Front-End data service:
frontEndApp.factory('requestsRepository',function ($http) {
var createServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "POST", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("createServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("createServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var updateServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "PUT", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("updateServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("updatetServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var getServiceRequests = function (successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
}).success(function (data, status, headers, config) {
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
var getServiceRequestById = function (Id,successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests/' + Id
}).success(function (data, status, headers, config) {
console.log("getServiceRequestById, data: " + data);
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
return {
createServiceRequest: createServiceRequest, getServiceRequests: getServiceRequests,
updateServiceRequest: updateServiceRequest, getServiceRequestById: getServiceRequestById
};
});
And here is my Back-End WebAPI:
public HttpResponseMessage Get()
{
var requestList = from req in new XPQuery<DummyRequest>(uow) select req;
List<AccountViewServiceRequest> dataList = new List<AccountViewServiceRequest>();
foreach(var item in requestList)
{
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
dataList.Add(sr);
}
var response = Request.CreateResponse(HttpStatusCode.OK, dataList.ToList());
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
public HttpResponseMessage Get(int Oid)
{
var item = (from req in new XPQuery<DummyRequest>(uow) where req.Oid == Convert.ToInt32(Oid) select req).First();
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
var response = Request.CreateResponse(HttpStatusCode.OK, sr);
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
Which part should I correct to successfully retrieve a single e record based on its OID?
Since it appears that your first issue is related to this routine:
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
Change the substring starting position to 1 to remove the prepended colon.
var getCleanId = function () {
return $routeParams.OID.substring(1, 2)
};
That in turn should fix the issue with not getting a single record out of the web api. The web api is trying to find a matching function signature in the controller on the web server. The only parameter can't convert to an integer, so it uses the Get() instead of the Get(int Oid).