How to pass argument to ASMX in angularjs - c#

I need to pass an id and get the related questions.
Error message - POST http://localhost:51949/API.asmx/GetAllQuestions/0 - 500 (Internal Server Error)
The web service works fine as I have checked in other part of C# code. Now, trying to access it from angularjs. Is this the right way?
app.js:
var app = angular.module('virtualApp', []);
controller.js:
app.controller("virtualController", function ($scope, DataFactory) {
$scope.categories=[];
$scope.GetAllQuestions = function (categoryId) {
DataFactory.GetAllQuestions(categoryId)
.success(function (data) {
$scope.categories = data;
})
.error(function (error) {
alert(error.message);
});
}
$scope.GetAllQuestions(0); //to fire at page load
});
services.js:
EDIT
app.factory("DataFactory",function ($http) {
var urlBase = "http://localhost:51949/API.asmx/";
var dataFactory = {};
dataFactory.GetAllQuestionCategories = function (categoryId) {
return $http.post(urlBase + "GetAllQuestions", { categoryId: categoryId })
.success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
return dataFactory;
});

I think problem with you code is you are passing id as part of url instead of it pass id in data of ajax request
Dont pass data in url like as below
//do not attach categoryId
urlBase + "GetAllQuestions/" + categoryId
instead of it pass data in data parameter of request like as below code
data: { test: 'test' }
and url will be urlBase + "GetAllQuestions
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' },
}
$http(req).success(function(){...}).error(function(){...});
one more thing you are calling function to get data than make use of Get method instead of Post method.

Related

How to recieve and process AngularJS HTTP POST to C#?

I'm developing a web site associated to a SQL database and Azure web app. The app support authentication. For now, I'm able to login a user using Owin OAuthAuthorizationServerProvider class.
Here is the code I'm using to POST login data from my Angularjs file :
fac.login = function (user) {
var obj = {
'username': user.username, 'password': user.password,
'grant_type': 'password'
};
Object.toparams = function ObjectsToParams(obj)
{
var p = [];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/token",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
userService.SetCurrentUser(response.data);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
And I deal with the data and identity by overriding : Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context).
This works perfectly. I'm now trying to create a "Sign In" page based on the same structure.
I think I know how to post the data with AngularJS like this :
fac.suscribe = function (newUser) {
var obj = {
'username': newUser.username, 'surname': newUser.surname, 'firstname': newUser.firstname,
'password1': newUser.password1, 'password2': newUser.password2, 'email': newUser.email, 'guid': newUser.guid
};
Object.toparams = function ObjectsToParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/register",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response){
userService.SetCurrentUser(response.data);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
But I wonder how I can get the data to generate the post answer. Any idea on C#, preferably ?
First, You should have Model same with same property name on the server side. So that the property that you are sending in the object from angularjs will get binded to the Model Properties. Instead of having headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, change it to headers: { 'Content-Type': 'application/json' } for the Web API.
For your reference i am sharing this link
CRUD WITH ANGULARJS and ASP.NET WEB API

Passing String into an API method with a Route Attribute

I have a method on an API Controller where I've set the route in an attribute, but I don't seem to be able to pass a string into this. When I try to hit this with an Ajax Request from the browser the console shows the following error:
BAD REQUEST - The request could not be processed by the server due to
invalid syntax.
The string I'm passing over is huge, but unfortunately is the only way I can import the data into the legacy application I'm working with. The test URL I'm using is (brace yourselves):
http://localhost:50915/api/job/import/ALMIG&sup3123456&sup32%20DAY%20ECONOMY&sup320170720&sup320170721&sup30&sup3&sup3&sup3&sup322&sup3Lara%20Croft%20Way&sup3Derby&sup3&sup3&sup3DE23%206GB&sup3Stuff&sup310&sup31&sup30&sup325&sup30&sup3&sup31%7CI%20Great%20Danger&sup30&sup30&sup30&sup3&sup3&sup30&sup3true&sup30&sup3&sup3&sup3&sup3&sup3&sup3&sup31&sup30&sup30&sup316&sup3Baden%20Road&sup3Stoke-on-Trent&sup3&sup3&sup3ST6%201SA&sup3&sup30&sup30&sup30&sup3&sup3&sup3&sup30&sup30&sup30&sup30&sup3&sup30&sup31&sup30&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3Liane&sup307730044916&sup3Lara&sup307730044916&sup30&sup3d2f0acf7-50e1-4a53-96ce-4fffd00b1a96&sup30
And the method is defined as below, the code inside is irrelevant as I put a break point on the start of the method which is never hit:
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/job/import")]
public int TmsImport([FromBody]string import)
{
// do something...
}
Edit: Added Ajax Request
job.confirmBookings = function () {
// TMS Import
job.toConfirmRow.filter(function(obj) {
var jobRow = obj;
var strArray = [];
for (var prop in jobRow) {
if (jobRow.hasOwnProperty(prop)) {
strArray.push(jobRow[prop]);
}
}
var joinedStr = strArray.join(job.seperator);
$.ajax({
type: "POST",
crossDomain: true,
data: joinedStr,
url: job.tmsString,
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr) {
console.log("TMS ID: " + data + " | " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
First format the route template correctly
[HttpPost]
[Route("api/job/import")] //Matches POST api/job/import
public int TmsImport([FromBody]string import) {
// do something...
}
Also you should post the data in the body of the request. If the payload is large then you do not want that in the URL

XMLHttpRequest cannot load URL. Invalid HTTP status code 400 (WebApi with angularJs on Chrome)

I have WebApi Application and a simple consuming web client. I am sending requests to webApi using angularJS from web client. And cors is already enabled of course.
I have had problems with Post on chrome but I fixed it using param to the object sent, I thought it would be the same for Put but I got 'XMLHttpRequest cannot load URL. Invalid HTTP status code 400' on chrome whereas it's working okay on IE.
C# code :
public void UpdateLampe(int Id, Lampe lampe)
{
var context = new eDomDataContext();
var found = context.Lampes.SingleOrDefault(p => p.Id == Id);
if (found != null)
{
found.Etat = lampe.Etat;
found.Date = DateTime.Now;
context.Lampes.Attach(found);
context.Entry(found).State = EntityState.Modified;
context.SaveChanges();
}
}
//Post request (works ok)
var lampe = $.param({'TypeObject': typeObject, 'SalleId': salleId});
$http({
method: "POST",
url: "http://localhost:1770/api/Lampe",
data: lampe,
headers: {'Content-Type': 'application/x-www-form-urlencoded',}
}).success(function (data) {
alert("it works");
}).error(function () {
console.log(Error);
alert('Error reading JSON file.');
})
.then(function (response) {
return response;
});
//Put request <= still have problem
var etat = $.param({'Etat' : false});
$http({
method: "PUT",
url: "http://localhost:1770/api/Lampe/1" ,
data: etat,
headers: {'Content-Type': 'application/x-www-form-urlencoded',}
}).success(function (data) {
alert("it works");
}).error(function () {
console.log(Error);
alert('Error reading JSON file. - ');
})
.then(function (response) {
return response;
});
Is there anything with what I did?
Thank you for your help.
I found a solution here : http://ask.webatall.com/iis/18460_asp-net-web-api-put-delete-verbs-not-allowed-iis-8.html
It was all about allowing the PUT & DELETE in the web.config
It might help someone.

pass header value in jQuery AJAX POST firefox

I called a Rest service in jQuery AJAX POST method. I need to pass two values in header.
Firefox neither pass the header value to the service nor calls the REST service. My Jquery code
var postCall = function () {
$.support.cors = true;
var HFAssoRefId = document.getElementById('MainContent_HFAssoRefId').value;
var Input = {
AssoRefId: HFAssoRefId
};
alert(JSON.stringify(Input));
var url = document.URL;
var name = "samuel";
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("PartnerName", name);
xhr.setRequestHeader("URL", url);
},
url: "http://localhost:40680/Service.svc/TokenInsertion",
data: JSON.stringify(Input),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
alert(status);
}
});
}
Is there any other methods to pass the header values in jQuery AJAX. It works fine with Internet Explorer 8. How to make it work compatible with Firefox browser also ?
I tried the other methods for posting like this.
Method 1 :
$(document).ready(function () {
$("#button").click(function(){
var name1 = "samuel";
var url1 = document.URL;
$.post('http://localhost:41855/IntegrationCheck/Default.aspx', {
name : name1,
url : url1
},function (data) {
alert(data);
});
});
});
and MEthod 2 in AJAX jQuery:
function setHeader() {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Accept', '');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "text/xml;application/json");
xhr.setRequestHeader("PartnerName", name);
xhr.setRequestHeader("URL", url);
}
But the header values are not passed and the service is not called in Firefox.
Any suggestions..
I used to follow the below approach to set request header. Please try it if works for you.
[Script]
$("#element").ajaxSuccess(function (evt, request, settings) {
$('.Status').html(request.getResponseHeader("Status"));
});
[View]
<h2>Status:</h2><h2 class="Status" style="color:Red;">
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Order orders)
{
string status = string.Empty;
if (orders != null)
{
OrderRepository.Update(orders);
status = "Updated";
}
Response.AddHeader("Status", status);
return data.GridActions<EditableOrder>();
}
Read about headers at jQuery.ajax.
Pass request headers in a jQuery AJAX GET call

ASP.Net MVC 3 Ajax query not firing

I have a very simple ajax call to refresh some data on my webpage, but it doesn't seem to fire correctly. The data that the call brings back is the same everytime even if the underlying data changes.
The ajax call looks like this:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
My controller looks like this:
public ActionResult ListByAjax(int Id)
{
var list = db.Address.Where(i => i.Person_Id == Id);
return PartialView("_List", list.ToList());
}
Try setting the cache to false in your ajax call - that will force the browser to send the request through to the controller:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
cache: false,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
Use
ajaxSetup({ cache: false }); });
This turns off caching for all ajax calls made by your app.

Categories

Resources