I am using WAP API, but don't know how to use ajax connect into the aaa method. Please help. same the ajax method cannot match [FromBody]Guid[] Ids, but how
[Route("aaa")]
[HttpPost]
public IHttpActionResult aaa(Guid teamId, [FromBody]Guid[] Ids)
javascript
var routeIds = new Array();
routeIds.push('EEBEEEDF-41F2-4931-41F2-362DDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
var team = { id: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06" };
var tmp = JSON.stringify({ teamId: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06", '': routeIds });
var path = GlobalData.url + "api/Event/UpdateRouteEnrollments";
$http({
method: 'POST',
url: path,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(tmp)
}).
success(function (data, status, headers, config) {
$scope.hide();
FeedStorage.save({ "id": data.TeamId, "Route": "0CE0F3C9-BB1E-4931-98F3-362DDE7BD406" });
$scope.setPlatform('team');
}).
error(function (data, status, headers, config) {
$scope.hide();
alert('An error occured:' + status);
});
Related
I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.
I can pass a model and string parameters into the controller, however, ints are not working for me.
I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.
Is there a way I can avoid this and just pass an int?
below is the code I am trying.
[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
//DO stuff with int here
}
here is the js.
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
The objId is always 0 in the controller.
I have tried this without doing JSON.stringify(data) as well with no result.
I have also tried all the different form attribute variations.
Try to use contentType as 'application/x-www-form-urlencoded':
var data = { objId: 1 };
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
Then remove the [FromBody] attribute in the controller
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//Do stuff with int here
}
I believe your issue could be that you are passing an object to the api, but trying to turn it into a primitive. I know there is already a chosen answer, but give this a whirl.
var data = { };
data["objId"] = 1; //I just wanted to show you how you can add values to a json object
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
You create a model class
public class MyModel {
public int ObjId {get;set;}
}
Your controller should expect one of these
[HttpPost]
public JsonResult PassIntFromView([FromBody] MyModel data)
{
//DO stuff with int here
}
JSON has a preference for strings not integers. You are better off to use JSON.stringify(data) to parse to your controller, convert that to a integer in the controller, then parse the string that was returned as:
var data = { objId: 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',//asp.net - url: 'api/controllerName/controllerFunction'
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
var result = JSON.parse(data);
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Try this:
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: data,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Your controller:
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//DO stuff with int here
}
Js
var data = { "objId": 1};
$.ajax({
url: "ControllerName/PassIntFromView",
data: data,
type: "POST",
dataType: 'JSON',
success: function(data.result!=null) {
console.log(data.result);
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
I got it working like this
let numberFour = JSON.stringify(4);
$.ajax({
.......
.......
data: numberFour,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
......
........
});
Here's my JS (jQuery and Ajax) code:
$('#submitSignUp').click(function () {
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({ name: name, email: email, password: password }),
success: function () {
alert("Rgistered.");
}
})
})
and this is my action method. (It's in "Home controller"):
[HttpPost]
public JsonResult SignUp(string name, string email, string password)
{
TodoNet.Models.TodonetModel database = new TodoNet.Models.TodonetModel();
TodoNet.Models.User oUser = new TodoNet.Models.User()
{
FirstName = name,
LastName = name,
Email = email,
Password = password,
Salt = password,
IsDeleted = false,
IsOnline = false,
PhoneNumber = "09212131212",
RegisterDate = DateTime.Now,
LastLoginDate = DateTime.Now
};
database.Users.Add(oUser);
database.SaveChanges();
return new JsonResult();
}
but I don't know why it doesn't work. after clicking on the '#signUpSubmit' button, the "alert("Registered.")" will not be shown.
What am I doing wrong??
Note: without using Ajax, (by using ordinary send form data to the action method, everything works properly (It means I know that there's nothing wrong with the back-end code)
If the form submitting normally works, then your ajax should be sending form data not json.
Also, prevent the default action of the button click.
$('#submitSignUp').click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: "json",
data: $("#the_form_id").serialize(),
success: function () {
alert("Rgistered.");
}
});
});
You can also do this way.
On your submitSignUp submit your parameter as following.
var param =
{
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: 'json',
data: JSON.stringify(param),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
success: function (data) {
alert(1)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
Change your controller:
[HttpPost]
public ActionResult SignUp(string name, string email, string password)
{
//other implementation
return Json("", JsonRequestBehavior.AllowGet);
}
Hope this helps!
Try this as your ajax method -
$('#buttonID').on("click",function() {
var data=
{
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
};
$.ajax({
url: '#Url.Action("SignUp","ControllerName")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function () {
alert("success");
}
});
});
I have this ajax request:
this.sendApiRequestWithFile = function (method) {
var formData = new FormData();
formData.append("name", "my name");
data_ajax = {
url: "http://localhost:1337/" + method,
method: "PUT",
data: formData,
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'multipart/form-data; boundary=----',
}
}
return $http(data_ajax).success(function(data, status, headers, config) {
return data;
}).error(function(data, status, headers, config) {
return data;
});
}
And my server is in sails.js so I catch parameters like this: req.body and it doesn't work. I try req.params.all() and doesn't work too.
I hope the following code should work. If you try to access the uploaded file from server, use req.file("file_name")
var fd = new FormData()
fd.append("name", "name value")
$.ajax({
url: "/url",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
console.log("Success : " + response);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});
I fairly new to Ajax post, and I wonder if someone could help me with why i keep getting the error message.
VideoController
[HttpPost]
public ActionResult Check(string userid, string streamid)
{
return Json(new { success = true });
}
The reason why the httppost is fairly empty yet is just to test if it works before i start writing the code.
Jquery
var userID = '#User.Identity.GetUserId()';
var defaultContext = window.location.hash === "" ? XSockets.Utils.guid() : window.location.hash.substr(1);
//alert(defaultContext);
$.ajax({
url: '/video/check',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: userID,
streamid: defaultContext
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function (error) {
alert(error.status);
}
});
I keep getting throw into my error: function and if I debug I never hit the [httpPost] Method
Can someone help
Update
I get a 404 in the alert.
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Try not to hardcore the URL:
var tURL = '#Url.Action("Check", "Video")';
$.ajax({
url: tURL ,
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: userID,
streamid: defaultContext
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
Server:
[HttpPost]
public JsonResult Foo(string userid, string streamid)
{
return new JsonResult{ Data = new {success = true}};
}
Client:
$.post('/home/foo',{userid:'123', streamid:'bar'}, function(r) {
console.log(r);
});
EDIT - If you prefer the $.ajax way instead of $.post:
$.ajax({
url: '/home/foo',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
userid: '123',
streamid: 'bar'
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
The confusing thing is that you mix XSockets.NET with AJAX... When you have XSockets in there, why pass anything over HTTP with AJAX? You can just as easy pass it to XSockets and call your service layer from there. Just a friendly pointer.
I'm trying to do an ajax post request on my MVC app, simply post data of form to server.
but I always get this error:
The required anti-forgery form field "__RequestVerificationToken" is not present.
This is my code for ajax request:
var reservationID = document.getElementById('ReservationID').value;
var arrival = document.getElementById('Arrival').value;
var departure = document.getElementById('Departure').value;
var noofrooms = document.getElementById('NoOfRooms').value;
var guestid = document.getElementById('GuestID').value;
var rateid = document.getElementById('RateID').value;
var agencyid = document.getElementById('AgencyID').value;
var sourceid = document.getElementById('SourceID').value;
var reservationtype = document.getElementById('ReservationType').value;
var reservation = { ReservationID: reservationID, Arrival: arrival, Departure: departure, NoOfRooms: noofrooms, GuestID: guestid, RateID: rateid, AgencyID: agencyid, SourceID: sourceid, ReservationTypeID: reservationtype };
var url = '/Reservations/Create';
$.ajax({
url: url,
type: "POST",
data : reservation,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
How can I add this anti-forgery field on my ajax?
For me this sollution works:
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajax("api/values", {
type: "post",
contentType: "application/json",
data: { }, // JSON data goes here
dataType: "json",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
</script>
taken from:
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API