Good evening SO, this been bugging me for a few hours already and still haven't figure out how to fix this.
All of my request data is fine except for subscriptionTag, it's value is always null whenever i send the request to server. I even tried removing JSON.stringify but it gives me false value instead.
Edit : Added HTTPPost in controller and type: post in javascript, i'm having an 500(internal server error) now :(
Edit 2 : Added Request Payload and Request URL
Request URL: http://localhost:49895/exclusive/send
Request Payload:
subscriptionTag=%7B%22IsAutomotive%22%3Atrue%2C%22IsMusicandDance%22%3Afalse%2C%22IsBeautyLifestyle%22%3Atrue%2C%22IsNighlifeEvent%22%3Afalse%2C%22IsFashion%22%3Afalse%2C%22IsRestaurantBar%22%3Afalse%2C%22IsHealthAndFitness%22%3Afalse%2C%22IsSportsOutdoor%22%3Afalse%2C%22IsHomeDecor%22%3Afalse%2C%22IsTravel%22%3Afalse%7D&pageid=33&emailAddress=gabyap1390%40gmail.com&token=cz0xJmV4Y2x1c2l2ZUlkPTM20&FirstName=Gabriel&source=%2Fsiggpay&MembershipLevelId=33
.NET
`
[HttpPost]
[Route("~/exclusive/send")]
public JsonResult Send(SubscriptionTag subscriptionTag, int pageid, string EmailAddress, string token, string FirstName = "", string source = "", int? MembershipLevelId = null)
{
return Json(new { error = false }, JsonRequestBehavior.AllowGet);
}
`
JAVASCRIPT
var subscriptionTag = {};
subscriptionTag.IsAutomotive = $('#IsAutomotive').is(":checked");
subscriptionTag.IsMusicandDance = $('#IsMusicandDance').is(":checked");
subscriptionTag.IsBeautyLifestyle = $('#IsBeautyLifestyle').is(":checked");
subscriptionTag.IsNighlifeEvent = $('#IsNighlifeEvent').is(":checked");
subscriptionTag.IsFashion = $('#IsFashion').is(":checked");
subscriptionTag.IsRestaurantBar = $('#IsRestaurantBar').is(":checked");
subscriptionTag.IsHealthAndFitness = $('#IsHealthAndFitness').is(":checked");
subscriptionTag.IsSportsOutdoor = $('#IsSportsOutdoor').is(":checked");
subscriptionTag.IsHomeDecor = $('#IsHomeDecor').is(":checked");
subscriptionTag.IsTravel = $('#IsTravel').is(":checked");
$.ajax({
url: MyAppUrlSettings.MyUsefulUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: {
subscriptionTag: JSON.stringify(subscriptionTag),
pageid: pageid,
emailAddress: emailAddress,
token: token,
FirstName: firstName,
source: source,
MembershipLevelId: membershipLevelId
},
success: function (result) {
if (result.error == false)
location.href = ""
}
});
},`
Just in case you might ask, heres my query string parameters.
subscriptionTag: {"IsAutomotive":false,"IsMusicandDance":false,"IsBeautyLifestyle":true,"IsNighlifeEvent":true,"IsFashion":false,"IsRestaurantBar":true,"IsHealthAndFitness":true,"IsSportsOutdoor":false,"IsHomeDecor":false,"IsTravel":false}
pageid: 33
emailAddress: gabyap1390#gmail.com
token: cz0xJmV4Y2x1c2l2ZUlkPTM20
FirstName: Gabriel
source: /siggpay
MembershipLevelId: 33
Thanks to all who commented on this but I managed to fix my problem I change my data from
data: {
subscriptionTag: JSON.stringify(subscriptionTag),
<code>some code here</code>
},
into
data: JSON.stringify({
subscriptionTag: subscriptionTag,
<code>some code here</code>
}),
Related
My ASP.net controller is receiving null instead of passed in parameters :(
Js function:
function SendFormToController() {
var username = document.getElementById("UsernameField").value;
var email = document.getElementById("EmailField").value;
var password = document.getElementById("PasswordField").value;
var SendJson = {
Username: username,
Email: email,
Password: password
};
console.log(JSON.stringify(SendJson));
$.ajax({
type: "POST",
data: JSON.stringify(SendJson),
url: "Register/Register",
contentType: "application/json"
});
}
Data is present when I console log it. But in the controller, I get - https://prnt.sc/u2mpa6
And it is for every field here
First; Did you add the [HttpPost] attribute on top of your controller method?
Second; If you submit it in 'querystring' format: Username=xx&Password=yy&... and use (HttpGet). Does that work?
If you need to do a POST (and not want to use GET) you can create an object with all your current arguments and use the [FromBody] attribute:
[Route("Register")]
[HttpPost]
public ResultData Register([FromBody] RegisterRequest data) {
//Your logic...
}
And client (JavaScript) side:
let url = 'http://...';
$.post(url, { Username: name, Password: pass, What: ever }, function (result) {
//Do some nice stuff
})
.fail(function (error) {
//Oh no! Show error.statusText
});
I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!
That's how I reach when I send some values that are specified in my input and therefore they need to send to a API.
When I try to send them to the monkey, my monkey tells me that nothing has been sent.
At my console.log(token), it tells me what data is available and I also agree that it all fits together. But the problem is just that it has to come over to my API.
function PayStripe() {
// Open Checkout with further options:
handler.open({
name: 'XXX ',
description: 'XX abonnement',
currency: "dkk",
amount: $('#HiddenPrice').val() * 100,
email: $('#Email').val()
});
};
// Close Checkout on page navigation:
$(window).on('popstate', function () {
handler.close();
});
var handler = StripeCheckout.configure({
key: 'pk_test_xxxx',
locale: 'auto',
token: function (token) {
token.subscriptionId = $('#SubscriptionId').val();
token.City = $('#City').val();
token.Postnr = $('#Postnr').val();
token.Mobil = $('#Mobil').val();
token.Adresse = $('#Adresse').val();
token.CVRVirksomhed = $('#CVRVirksomhed').val();
console.log(token.subscriptionId);
console.log(token);
$.ajax({
type: "POST",
url: "/api/Stripe",
contentType: "application/json",
data: token,
success: function (data) {
//window.location.href = '/Subscriptions/Succes';
alert(data + "Succes")
},
error: function (data) {
console.log(data + "Error");
},
dataType: 'json'
});
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
Where the problem lies is that the API is by no means able to get informed information from jquery. so it's like it can not / will receive it.
[HttpPost]
[Route("api/Stripe")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromForm] JObject token)
When I grab the token that I need for example. then I do this here:
var SubscriptionId = (int)token.GetValue("subscriptionId");
When you set contentType: "application/json", you need to stringify the data to json yourself
data: JSON.stringify(token),
I been looking around for awhile now and have came across this question many times and I am doing the same thing that are in the solutions but baffled why its not working.
I'm sure this question will be marked as a duplicate, and it is, but I am missing something.
Here is the array of JavaScript objects
var gridData = {
tempData: [
{ UserName: "Tom", LastName: "Solomon" },
{ UserName: "Harry", LastName: "Solomon" },
{ UserName: "Sally", LastName: "Solomon" },
{ UserName: "Dick", LastName: "Solomon" },
]
};
Here is my Ajax
function TossIt() {
var sendThis = gridData.tempData;
console.log(sendThis);
$.ajax({
type: "POST",
url: "/Junk/JAT?s=" + sendThis,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendThis),
success: function (data, textStatus, jqXHR) { },
complete: function (e) {
}
})
}
Here is the method I am passing it to
[HttpPost]
public List<Stuff> JAT(Stuff s)
{
List<Stuff> result = new List<Stuff>();
return result;
}
and here is the class
public class Stuff
{
public string UserName { get; set; }
public string LastName { get; set; }
}
I have a break point on the JAT method and s is always null
EDIT
I need to manipulate some of the properties in objects then return the list
There are a number of issues with your code
You cannot send a javascript array of objects in a query string
parameter and your url needs to be just url: '/Junk/JAT',, or
preferably url: #Url.Action("JAT", "Junk"); which will ensure the
url is correctly generated (as a side note, to bind the model from a
query string, it would need to be
/Junk/JAT?[0].UserName=Tom&[0].LastName=Solomon&[1].UserName=Harry&.....)
Your sending an array of objects representing a Stuff, therefore
the parameter in the POST method must also implement
IEnumerable<Stuff> (not a single Stuff)
Your specifying that the method return json (your use of dataType: "json",) so therefore the method must return a JsonResult.
You code should be
Script
$.ajax({
type: "POST",
url: '#Url.Action("JAT", "Junk")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ s: sendThis }),
success: function (data, textStatus, jqXHR) {
.... // do something with the data you return
},
complete: function (e) {
}
})
Controller
[HttpPost]
public JsonResult JAT(List<Stuff> s) // or ActionResult
{
.... // manipulate the collection as required
return Json(s);
}
[HttpPost]
public List<Stuff> JAT([FromBody]List<Stuff> s)
{
List<Stuff> result = new List<Stuff>();
return result;
}
The answer above using POST is the way to go. However, if you want to do GET and queryStrings, you can as well.
Trivial example:
Client side (see $.param())
var gridData = {
tempData: [
{ UserName: "Tom", LastName: "Solomon" },
{ UserName: "Harry", LastName: "Solomon" },
{ UserName: "Sally", LastName: "Solomon" },
{ UserName: "Dick", LastName: "Solomon" },
]
};
function TossIt() {
var sendThis = gridData.tempData;
console.log(sendThis);
$.ajax({
type: "GET",
url: "/JAT?" + $.param(gridData), //using $.param() here for query string
success: function(data, textStatus, jqXHR) {},
complete: function(e) {
}
});
}
Controller side
follow the above comments/answer regarding List<Stuff>
HttpGet Attribute
Adjust the parameter name to tempData (re: $.param())
[System.Web.Mvc.HttpGet]
public List<Stuff> JAT(List<Stuff> tempData)
{
......
}
Hth...
I'm having a problem with my JSON response in my MVC 3 application. When JSON is responding, my browser cannot handle application/json and tries to open it as a file. However, I'm recieving the correct data in the file.
I've added this to my Global.asax file:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
This is my javascript code:
$('#register).submit(function () {
if ($(this).valid()) {
var ai = {
Firstname: $("#Firstname").val(),
Lastname: $("#Lastname").val(),
Email: $("#Email").val()
};
var json = $.toJSON(ai);
$.ajax({
url: '/Person/Create',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Error");
}
})
}
});
And this is my ActionResult method:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Personer.Add(person);
db.SaveChanges();
}
return Json(new { Success = person.ID > 0, Firstname = person.Firstname, Lastname = person.Lastname });
}
I've also added .json (application/json) to the MIME-list in IIE.
If you're trying to access a file with JSON headers in Firefox directly (meaning: you're entering the URL into the address bar), Firefox will download it as a file. However, when you call your JSON in an AJAX request, it'll work the way you want it to.