What is the issue with asp.net route - asp.net

This is from asp.net 5 / mvc 6. I have two controller methods, each takes a single parameter and each returns a string. One method takes a string parameter and the other takes a simple object. The method that takes the string parameter does not work (the value for the incoming parameter is always null). The call that passes in the simple object does work. I am making the calls to these methods from inside an angular controller using the $http service. I must be doing something wrong that is very simple, but I don't see it.
Here is the code for the controller class:
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpPost("PostWithStringParam")]
public string PostWithStringParam([FromBody] string val)
{
return val ?? "<null>";
}
[HttpPost("PostWithInputparam")]
public string PostWithInputParam([FromBody] TestInputClass val)
{
string ret = "<null>";
if (val != null)
{
ret = $"First Name: {val.Name}, City: {val.City}";
}
return ret;
}
}
Here is the relevant code from the angular controller. Note the the "go" function is wired up to ng-click from a button.
vm.inputObject = {
name: "George",
city: "Chicago"
}
vm.inputString = "some data";
var callApi = function(url, data) {
$http({
method: "POST",
url: url,
data: data
}).then(
function (result) {
alert(result.data);
},
function (error) {
alert(error.status);
}
);
}
var callStringApi = function() {
var url = "api/values/PostWithStringParam";
callApi(url, vm.inputString);
}
var callObjectApi = function () {
var url = "api/values/PostWithInputParam";
callApi(url, vm.inputObject);
}
vm.go = function() {
callStringApi();
callObjectApi();
}
Can someone please tell me why the method that takes the input string doesn't work??
Thanks!

You need to strinfigy the data and specify the contentType as application/json when sending data. The default model binder will be able to map the posted data then.
var callApi = function(url, data) {
$http({
method: "POST",
url: url,
data: JSON.stringify(data),
contentType:"application/json"
}).then(
function (result) {
alert(result.data);
},
function (error) {
alert(error.status);
}
);
}

Related

Using AngularJs $resource and jquery bind

I'm new to Angualrjs and I'm trying to figure out this code... this is how the service looks like
var userGroupServices = angular.module('userGroupServices', ['ngResource']);
userGroupServices.factory('UserRoles', ['$resource', function ($resource) {
var r1 = $resource('/api/UserRoles/:UserRoleId', null, {
'update': { method: 'PUT' },
'delete': { method: 'DELETE' }
});
r2 = $resource('/api/UserRoles', null, {
'add': { method: 'POST' },
'getRoles': { method: 'GET' }
});
r3 = $resource('/api/UserRoles/GetRolesByGroupType/:groupTypeName', null, {
'getRolesByName': {method:'GET'}
});
r1.getAll = r2.getRoles.bind(r2);
r1.add = r2.add.bind(r2);
r1.getRolesByName = r3.getRolesByName.bind(r3);
return r1;
}]);
Why is it in the end, you bind r2 and r3 variables into r1 variable? how do i use this factory to POST something, i try to post it like this way but it didn't do anything(in my controller)...
addService.addRole({ roleName: groupTypeName });
I think the reason why resources 2 and 3 are being combined and returned by resource 1 is to abstract these other resources away from someone who wants to use the UserRoles service. Now you don't need to know about how many resources the service needs in order to work.
As for posting, .addRole() doesn't seem to exist in your service. Try UserRoles.add({object}).

angular service and http request

creating service
myApp.factory('serviceHttp', ['$http', function(http) {
http.get($scope.url).then(function(result){
serviceVariable = result;
}
return serviceVariable;
}
Controller
function appController($scope, serviceHttp){
$scope.varX = serviceHttp;
if(serviceHttp){
// decision X;
} else {
// decision Y;
}
}
view:
input(ng-if='varX') serviceHttp Exist
input(ng-if='!varX') serviceHttp noExist
The above code always shows varX not exist because app installs during http call of service. I want to use angular service to inject variables from server to make decision at time of booting the application.
Try to rewrite factory by this way that returns promise:
myApp.factory('serviceHttp', ['$http', function(http) {
var factory = {
query: function () {
var data = http.get($scope.url).then(function(result){
return result;
},
function (result) {
alert("Error: No data returned");
});
return data;
}
}
return factory;
}]);
From controller:
serviceHttp.query().then(function (result) {
$scope.varX = = result;
}
Here is Demo Fiddle
in demo we used other URL source
If i correct understand you, you should doing it like this:
var app = angular.module('YourModule', []);
app.factory("serviceHttp", function($http) {
var serviceHttp={};
serviceHttp.yourGetRequest = function(yourUrl) {
return $http.get(yourUrl);
};
return serviceHttp;
});
And for example, controller:
var Controller = function($scope,serviceHttp) {
$scope.varX='';
$scope.loading = true;
var returnArr = serviceHttp.yourGetRequest($scope.url).success(function(dataFromServer) {
$scope.loading = false;
$scope.varX = dataFromServer;
})
};
in view you can use ng-show, like this:
<div ng-show="loading" class="loading"><img src="../styles/ajax-loader-large.gif"></div>
When your application start loading, $scope.loading = true and this div shown, and when you get response from server $scope.loading became false and div doesn't show.

Not able to retrieve if the parameter starts with zero when passing from jquery to my webmethod

My Problem looks really strange, I am calling an Autocomplete.asmx web method from jQuery. Thew first time the first parameter, 0, is passing, and the second time the zero is getting replaced, instead of 0, any other numbers are getting displayed.
Aspx:
function SearchText() {
$('#<%=txtphoneno.ClientID%>').autocomplete({
source: function (request, response) {
Search();
}
});
}
//-->loadtop 5 jobs
function Search() {
var callid = $('#<%= txtphoneno.ClientID%>').val().toString();
// alert(callid);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../HttpHandler/Autocomplete.asmx/GetCallername",
data: "{'callerid':" + callid + "}",
dataType: "json",
success: function (data) {
//response(data.d);
// alert(data.d);
$('#<%=txtname .ClientID %>').removeClass('text-label');
$('#<%=txtname .ClientID %>').addClass('lbls');
$('#<%=txtnote .ClientID %>').removeClass('text-label');
$('#<%=txtnote .ClientID %>').addClass('lbls');
document.getElementById('<%=txtname .ClientID %>').value = data.d[0];
document.getElementById('<%=txtnote .ClientID %>').value = data.d[1];
if (data.d != 'User Doesnt Exist') {
var param = $('#<%= txtphoneno.ClientID%>').val();
$("#<%=IframeJobHistory.ClientID%>").show();
LoadHistoryDetails(param);
}
else {
// $("#<%=IframeJobHistory.ClientID%>").hide();
}
},
error: function (result) {
// alert("Error");
}
});
}
** CS Code AutoComplete.Asmx**
[WebMethod ]
public string [] GetCallername(String callerid)
{
..............................
return CallerDetails;
}
}
In the String callerid, the first time when the user enters 0 I am getting back 0, but second time when the user enters any number I am getting the number but the Zero disappears.
If i use any other number,apart from zero things are working fine.
instead of using zero try to use -1
Sorry , I don't know what you missed , But I know the simple one
solution for your issue .
Just add this code for dynamically add 0 if the first value is not zero, Otherwise it's diaplayed your default value
Put break point and check
[WebMethod ]
public string [] GetCallername(string callerid)
{
string Filteredcallerid = !string.IsNullOrEmpty(callerid) ? callerid.Substring(0, 1) : "";
callerid = Filteredcallerid != "0" ? "0" + callerid : callerid;
return CallerDetails;
}

Post Form data from extjs4.2 to Spring Controller

Here is my extjs 4.2.1 data store :
Ext.define('APP.store.CompanyStore', {
extend : 'Ext.data.Store',
requires: 'APP.model.Company',
model : 'APP.model.Company',
proxy: {
type : 'ajax',
url : 'searchP.html',
actionMethods :{read:'POST'},
reader : {
type: 'json',
root: 'items'
}
}
Here is my action on Submit :
var pname = Ext.getCmp('pname ').getValue();
var SearchObj = Ext.getCmp('searchForm').getValues();
SearchObj.pname =pname;
var store = Ext.getStore('APP.store.CompanyStore');
store.load({
params:{
"SearchObj" :Ext.encode(SearchObj)
},
callback: function(records, operation, success) {
// the operation object
// contains all of the details of the load operation
console.log(records);
}
});
My problem :
The object is not getting mapped to the POJO defined at server side in my Spring controller.What may be the problem.
My Spring Controller:
#RequestMapping(value = "/searchP", method = RequestMethod.POST)
public #ResponseBody String searchP(#RequestBody Company company){
System.out.println("pname"+company.getPName()); //getting null.Not getting actual value.
return "item";
}

Calling a specific method in my Web API controller

So I'm trying to make a call to this specific method:
[HttpGet]
public int GetLogin(string u, string p)
{
UserLogin uL = new UserLogin();
return (int)uL.Authenticate(u, p);
}
However it keeps calling this method in my Controller instead:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
^^ Which is the generated code in the Controller.
Here Angular code for my factory and, more importantly, my URI:
var loginFactory = angular.module('loginService', ['ngResource'])
loginFactory.factory('UserLogin', function ($resource) {
return $resource('api/login?:username?:password', {}, {
query: {
method: 'GET',
params: { username: 'hunter', password: 'hunter' },
isArray:true
}
});
});
Any insight would be much appreciated. Thanks.
Change your resource to this:
$resource('api/GetLogin?u=:username&p=:password', {}, { // if that's the right route
query: {
method: 'GET',
params: { username: 'hunter', password: 'hunter' },
isArray:true
}
});
Is your request going like api/login?username=something&password=something...?
if yes, the parameter names on the action should match the query string parameter names:
public int GetLogin(string **username**, string **password**)

Resources