how to get data from WebMethod in angular2 - http

In Javascript using Ajax
$.ajax({
type: "Get",
url: "AttendanceMaster.aspx/GetDistinctBatch",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function(response) {
},
error: function(response) {
alert("(allstudent )" + response.status + ' Error ' + response.statusText);
}
});
tried following for angular2
return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
.map((response) => response.toString());
it returns
{ "_isScalar": false, "source": { "_isScalar": false }, "operator": {} }
C#
[System.Web.Services.WebMethod]
public static string GetDistinctBatch()
{
return "welcome Angular 2";
}
1) how to use in angular2?
See Error below

Your method is just returning Observable, they will just sit as a function. Observable are lazy in nature. They wouldn't get executed until you subscribe to them.
AttendanceMast() {
return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
.map((response) => response.toString()); //better do it response.json();
}
myService.AttendanceMast().subscribe(
data => console.log(data);
)

dataservice
getwithParamter(): Observable<JSON> {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json; charset=utf-8');
let options = new RequestOptions({
method: RequestMethod.Post,
url: "AttendanceMast.aspx/HelloWorldss",
headers: this.headers,
body:{program: 'pravin'} //same like data: "{}" in ajax
});
return this._http.request(new Request(options)).retry(2)
.map((response: Response) => response.text())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
C#
[System.Web.Services.WebMethod]
public static string HelloWorldss(string program)
{
return "welcome Angular" + program;
}
call
this.dataService.getwithParamter().subscribe(
tradeshows => this.getwithparamter = tradeshows,
error => console.error('Error: ' +error)
);
print this variable showing your output this.getwithparamter

I assume you are using the standard configuration for a WebService. If so, I believe your problem is that your are using the inbuilt rest capability of Angular2 to access a WebService, aka a Soap service, returning xml soap envelopes. Hence the 404.
Unfortunately, you have a bit more work to do to make it work than if you were accessing a rest service.
Have a look at angular2-soap on github. It should get you on the right track.

Related

ASP.Net MVC Getting HTTP 400 with ajax post request

I am trying to post some simple data with ajax from my view to controller. When I switch it to HttpGet it works fine, but when trying httppost I always get error 400.
Here is my view code:
#Html.Hidden("postSettings", Url.Action("MethodName", "MyController"))
$.ajax({
url: $("#postSettings").val(),
type: "POST",
data: JSON.stringify(11),
dataType: "json",
contentType: "application/json",
success: function (_result) {
console.log("success")
},
error: function (e) {
console.log(e);
}
});
And code in my controller:
[HttpPost]
public IActionResult MethodName(object value)
{
return Ok();
}
I did not noticed that I have global filter applied
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
,adding the CSRF token fixed the problem.
I just added this code to my view:
<script type="text/javascript">
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
</script>
And to the ajax request:
headers: {
RequestVerificationToken: gettoken()
},

How do I pass along json patch data with rest client in asp.net?

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 get "Get" web service instead of "POST" web service

I have used this post Jquery Ajax Posting json to webservice to send data to the server via "POST" web service,but it has been traited like a "Get"
in "Network" section of the browser,this is what I get:
this is my code for the web service(ASP.net):
// Insert Student
[Route("api/Students/ajout")]
[System.Web.Http.ActionName("Create")]
public async Task<HttpResponseMessage> Post(Student value)
{
try
{
if (ModelState.IsValid)
{
_StudentService.Insert(value);
var response = Request.CreateResponse<Student>(HttpStatusCode.Created, value);
await _unitOfWorkAsync.SaveChangesAsync();
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Model state is invalid");
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
and this is my code (AngularJS)
$.ajax({
type: 'POST',
url : 'http://localhost:50001/api/Students/ajout',
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
data: { FirstName: ''+$scope.FirstName+'', LastName: ''+ $scope.LastName+'' , Email: ''+ $scope.Email+'' , DropOut:'' +$scope.dropout.value1+'' , Live: ''+$scope.live.value2+'' , ClassId:2, ImageId:1}, // On fait passer nos variables, exactement comme en GET, au script more_com.php
success: function(data){
console.log("success");
},
failure: function(errMsg) {
console.log(errMsg);
}
});
have you please any idea how can I deal with this problem,thanks a lot for help
Update:
I have changed the code like that:
$.ajax({
type: 'POST',
url : 'http://localhost:50001/api/Students/ajout',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { FirstName: ''+$scope.FirstName+'', LastName: ''+ $scope.LastName+'' , Email: ''+ $scope.Email+'' , DropOut:'' +$scope.dropout.value1+'' , Live: ''+$scope.live.value2+'' , ClassId:2, ImageId:1}, // On fait passer nos variables, exactement comme en GET, au script more_com.php
success: function(data){
$rootScope.usersData = angular.toJson(data);
console.dir($rootScope.usersData);
console.log("success");
},
failure: function(errMsg) {
console.log(errMsg);
} });
but I get this error:
XMLHttpRequest cannot load http://localhost:50001/api/Students/ajout. Response for preflight has invalid HTTP status code 405
In your api try to remove [Route("api/Students/ajout")] and instead of [System.Web.Http.ActionName("Create")] put [HttpPost].
In your controller, I advise you to use angularjs queries rather than the ajax requests.
this request should run if you edit your api controller:
var request = $http({
url:"api/students/",
dataType:"json",
method:"POST",
data:JSON.stringify(student),//you can send directly the object student if is well-trained or use params:{'name':value, ...}
contentType:"application/json; charset=utf-8"
});
And in your Api controller to recovered your object if you use JSON.stringify change your method for :
[HttpPost]
public void CreateStudent([FromBody]Student value)
{
...
}
I don't know if you do, but in your html instead of bind the property firstname on your input, bind student.firstName. Like this, you can recover directly $scope.student with the property $scope.student.firstName instead of recover each property one by one. And so send directly the object like I put in example.
So I hope this will helpfull.
Keep me informed of your progress. Have nice day.

Controller post returning View but doesn't display the View

I have a View.cshtml file in ViewController which has a hyperlink. Upon clicking the link, I call an ajax request to POST to a GreetingController action:
[HttpPost]
public async Task<ActionResult> Welcome(MyModel model)
{
ActionResult result = null;
Task<bool> createTask = Helper.Create(model);
try
{
bool success = await createTask;
if (success)
{
result = View();
}
else
result = new HttpNotFoundResult("Specified resource was not found.");
}
catch
{
result = View("Error");
}
return result;
}
If the method in the POST is succesful, I set the result to the View property. I have a Welcome.cshtml view for this Action and I was expecting it to display that but it doesn't. Instead of returning View, I tried returning a RedirectToAction and created a GET version of the Welcome action, but still it didn't show. Can someone explain what I am doing wrong?
EDIT:
The AJAX call:
$.ajax({
type: "POST",
url: "/greeting/welcome",
data: JSON.stringify(model),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (xhr, err) {
}
});
Also, the return call above was originally "return View()". I've changed it to "return result".

asp.net web api 2 attribute route is not found

I have this route in an API controller called Recruiting:
ResponseType(typeof (int))]
[Route("Recruiting/setprimary/")]
public async Task<IHttpActionResult> PutUpdatePrimary(string userId, string orgId)
{
return Ok();
}
I am trying to hit this routing via ajax like so:
self.updatePrimary = function () {
var orgKey = self.selectedOrgKey();
alert(orgKey);
$.ajax({
type: "PUT",
contentType: "application/json; charset=utf-8",
url: "/Recruiting/setprimary/" + "?userId=" + userId + "&?orgId=" + orgKey,
data: null,
dataType: "json",
success: function (data) {
bootbox.alert('Changes saved successfully.');
},
error: function (err) {
bootbox.alert('An error occured while trying to set primary organisation. Please try again :/');
}
});
return true;
};
Fiddler is saying it cannot find the route. What do I have wrong here?
Looks like you have a typo in your request url: Instead of "&?orgId="..it should be "&orgId="

Resources