I get "Get" web service instead of "POST" web service - asp.net

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.

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()
},

The action method is fired, but value of the passed parameter is null

I use ASP MVC 5.
I try to send data from client to action method on the server.
Here is data that I sent:
var layer = {
layeType:"Vector"
layerName:"aaaa"
mapId:5
}
And here is ajax method:
function saveLayer(layer, callback, error) {
return $.ajax({
url: '/Mobile/Layer/SaveLayer',
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { layer: layer },
success: callback,
error: error
});
Here is action method:
public JsonResult SaveLayer(string layer)
{
return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}
The action method is fired, but value of the layer is null.
Any idea why value is null and how to fix it?
Ok,
Firstly, you are trying to send a complex object through on a GET request. GET requests don't have a body, they are limited to transferring data through the Url, so it would need to be a query string parameter.
Secondly, following rest conventions, GETs are idempotent, in that, each action should not have a side effect, calling it repeatedly should yield the same result.
I would switch your method to a POST, as that will more accurately convey that you are going to be causing a side effect on the server.
After you have done that, I would make a model in C# that matches the json structure that you are passing in, then you will get a value through.
Class
public class Layer
{
public string LayeType {get;set;}
public string LayerName {get;set;}
public int MapId {get;set;}
}
Javascript
function saveLayer(layer, callback, error) {
return $.ajax({
url: '/Mobile/Layer/SaveLayer',
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { layer: layer },
success: callback,
error: error
});
Function
public JsonResult SaveLayer(Layer layer)
{
return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}
That should sort it
First -
Make the type from GET to POST
Second -
Change the parameter type from string to Object type, i.e. Layer
The properties in Layer class should match the json data you are sending.
public JsonResult SaveLayer(Layer layer)
{
return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}

Passing multiple parameters with Ajax

I have a function in my .aspx page where I collect the first name and last name from the user and would like it to pass back to the server side code(c#). Ajax is being used and runs fine when one parameter is passed, although when a second parameter is passed I receive an error : can someone shed a little light, thanks
ERROR:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
POST http://ingleParam.aspx/GetCurrentTime 500 (Internal Server Error) jquery-.11.1.min.js:4
send jquery-1.11.1.min.js:4
m.extend.ajax jquery-1.11.1.min.js:4
ShowCurrentTime SingleParam.aspx:12
onclick
.ASPX Code
function ShowCurrentTime() {
$.ajax({
type: "Post",
url: "SingleParam.aspx/GetCurrentTime",
data: { name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Server Side Code:
[WebMethod]
public static string GetCurrentTime(string name, string lastname) {
return "Hello " + name + Environment.NewLine + "The current time is " + DateTime.Now.ToString();
}
I've had issues with sending json objects to webmethods. I've had success when I stringify the data being sent across. Like so:
data: JSON.stringify({name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val()}),
Give that a try and see if it helps.

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="

$.ajax success not executing

I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]

Resources