I am trying to POST data to an Asp.Net Web API on another one of my domains. I need to support IE9/8 so CORS won't cut it. When I make a call like this:
$.ajax({
type: "GET",
url: "http://www.myotherdomain.com/account",
data: "{firstName:'John', lastName:'Smith'}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(msg) {
console.log(msg);
},
error: function(x, e) {
console.log(x);
}
});
it makes a GET request to:
http://www.myotherdomain.com/account?
callback=jQuery18008523724081460387_1347223856707&
{firstName:'John',%20lastName:'Smith'}&
_=1347223856725
I've implemented this JSONP Formatter for ASP.NET Web API and my server responds with a properly formatted JSONP response. I don't understand how to register a route to consume an account object.
config.Routes.MapHttpRoute(
name: "Account",
routeTemplate: "account",
defaults: new { controller = "account", account = RouteParameter.Optional }
);
How do I deserialize an object from a querystring parameter without name?
Instead of using JSON you could send the parameters as query string values. Let's suppose that you have the following model:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
and the following API controller:
public class AccountController : ApiController
{
public HttpResponseMessage Get([FromUri]User user)
{
return Request.CreateResponse(HttpStatusCode.OK, new { foo = "bar" });
}
}
which could be consumed like that:
$.ajax({
type: 'GET',
url: 'http://www.myotherdomain.com/account?callback=?',
data: { firstName: 'John', lastName: 'Smith' },
dataType: 'jsonp',
success: function (msg) {
console.log(msg);
},
error: function (x, e) {
console.log(x);
}
});
Related
I have below lines of code in controller, model and in js file.
I am able to make call to controller, but model properties are always null.
...
[HttpPost]
public IActionResult CreateBooking(Country request)
{
return Ok();
}
public class Country
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
var request = {
name: 'Prateek',
code: 'US'
};
$.ajax('/Home/CreateBooking', {
data: JSON.stringify({ request }),
contentType: 'application/json',
type: 'POST',
dataType: 'json',
success: function (response) {},
error: function(response){}
Can anyone help please?
Thanks in advance
var request = jQuery.parseJSON('{ "Name": "Prateek", "Code": "US" }');
$.ajax({
url: "/Home/CreateBooking",
type: "POST",
dataType: "JSON",
data: request,
success: function (d) {
},
error: function (d) {
console.log(d);
}
});
My serverside (ASP.NET MVC) has this action:
[HttpPost]
public JsonNetResult MyAction(long param1, string param2, string stringifiedJson)
{
...
}
With JQuery I can use this action easily, like this:
$.ajax({
async: true,
type: 'POST',
url: '/bla/myAction',
data: {
"param1": 123,
"param2": "blah",
"stringifiedJson": JSON.stringify(someJSON),
},
success: function (data) {
...
}
});
But with angularjs, I haven't been able to do the request. This is what I'm trying:
var httpRequest = $http({
method: "post",
url: "/bla/myAction",
params: {
param1: 123,
param2: "blah",
stringifiedJson: JSON.stringify(someJSON)
},
data: {
}
});
httpRequest.success(function(response) {
...
});
In fact, angularjs isn't even doing a HTTP POST.. it is doing a OPTIONS request so I'm getting 404 not found.
Question is... how can I do a post request with params? I know I could use "data" but then, how do I make ASP.NET MVC to map the request to each method parameter?
The data you are sending should have the same names as the asp.net mvc method parameters.
f.e
if u have method
public ActionResult doSomethingMethod(string name, string surname)
{
//code
}
from angularjs:
$http({
url: "your url",
method: "POST",
data: {
name: "Jon",
surname: "Doe"
}
})
there is also quicker way
var dataToSend = {name:"Jon",surname:"Doe"};
$http.post("your url",dataToSend);
I have looked over the net to figure out what my mistake is. All suggestions I found I tried, without any succes. I access the httppost action in my controller but the parameters stays empty.
AJAX function
var dataPost = { 'id': id, 'val': val };
debugger;
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: dataPost ,
contentType: 'json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
On debug DataPost is populated.
Controller
[HttpPost]
public ActionResult UpdateJson(string id, string val)
{
//do stuff
return Json(true);
}
The parameters I used in my controller have the same name as in my Ajax function. The format passed is json, I have also tried populating my data with:
var dataPost = { 'id': 'id', 'val': 'val' };
But this doesn't make any difference. I have also tried to work with a Class, like -->
Class
public class ScheduleData
{
public string id { get; set; }
public string val { get; set; }
}
Controller
public ActionResult UpdateJson(ScheduleData data)
{//Do something}
Any help would be appreciated. Thanks in advance
The format passed is json
No, not at all. You are not sending any JSON. What you do is
data: { 'id': id, 'val': val }
But as the documentation clearly explains this is using the $.param function which in turn uses application/x-www-form-urlencoded encoding.
So get rid of this contentType: 'json' property from your $.ajax call.
Or if you really wanna send JSON, then do so:
var dataPost = { 'id': id, 'val': val };
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: JSON.stringify(dataPost),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
Things to notice:
usage of JSON.stringify(dataPost) to ensure that you are sending a JSON string to the server
contentType: 'application/json' because that's the correct Content-Type value.
I want to send JavaScript object array as list object to server, the server side method(GetData) accepts list object with 3 elements, but all elements have null value. Any advice? Thanks in advance.
At Client:
User.js
define(function () {
function User(name) {
this.Name = name
}
return User;
});
main.js
var users = [new User('Barney'),
new User('Cartman'),
new User('Sheldon')];
$.ajax({
type: "POST",
url: "/Home/GetData",
data: {users: users},
success: function (data) {
//alert(data.Result);
},
dataType: "json"
});
At Server:
GetData action
public void GetData(List<User> users){
}
User Model
public class User {
public string Name { get; set; }
}
I changed main.js like below, and it worked:
main.js
var params = {'users': [new User('Barney'),
new User('Cartman'),
new User('Sheldon')]};
$.ajax({
type: "POST",
url: "/Home/GetData",
data: JSON.stringify(params),
success: function (data) {
//alert(data.Result);
},
contentType: "application/json"
});
I am sending json data to my controller action via jquery ajax post. The IEnumerable in my action is alway null.
Is my json wrong or why does the model binder not convert the json to the IEnumerable ?
public ActionResult Update(IEnumerable<Teststep> teststeps)
{
//
}
$.ajax({
url: '#Url.Action("Update", "Teststep")',
type: 'POST',
data: [{ "errortext": "oh something bad happended.", "unitid": "10" }, { "errortext": "you got it man.", "unitid": "20"}],
success: function (response) {
debugger;
if (response.success) {
dlg.dialog("close");
// Update UI
}
else {
// Reload the dialog with the form to show model/validation errors
dlg.html(response);
}
}
});
public class Teststep
{
[HiddenInput(DisplayValue = false)]
public int UnitId { get; set; }
public string ErrorText { get; set; }
// some other props removed for readability
}
In order to get collections (arrays, ienumerables, etc) to pass correctly through the modelbinder to the action method, I've always had to set the traditional: true option on the ajax call:
$.ajax({
url: '#Url.Action("Update", "Teststep")',
type: 'POST',
traditional: true,
...
Now it works! I get 1 item in the IEnumerable. The problem was the messed up json ;-)
var data = { teststeps: [{ ErrorText: 'bla', UnitId: 10}] };
$.ajax({
url: '#Url.Action("Update", "Teststep")',
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json'
});
[HttpPost]
public ActionResult Update(IEnumerable<Teststep> teststeps)
{
}