Ajax send array and bool to controller method
I've been trying to send an array of objects to a controller method using AJAX, but even after trying various methods I still won't get my desired result. This is my current code:
View
function SaveGame() {
if ('@Session["Username"]' == '@Model.Player1.Username') {
p1 = true;
}
else {
p1 = false;
}
var characters = document.getElementsByClassName("char");
var chardata = ;
for (var i = 0; i < characters.length; i++) {
var id = characters[i].id;
var state = characters[i].classList[1];
chardata.push(id, state);
}
console.log(chardata);
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'GET',
data: JSON.stringify({ 'character': chardata }),
cache: false,
contentType: 'application/JSON',
success: function (result) {
alert("Game Saved");
}
});
}
Gamecontroller/SaveGame
public bool SaveGame(JsonDecode character)
{
ViewGame game = (ViewGame)TempData["game"];
TempData["game"] = game;
return true;
//return charLayer.SaveCharacters(game.Id, ids, states, isPlayer1);
}
character
will just be null
JsonDecode
public class JsonDecode
{
public object chardata { get; set; }
}
c# ajax asp.net-mvc
|
show 2 more comments
I've been trying to send an array of objects to a controller method using AJAX, but even after trying various methods I still won't get my desired result. This is my current code:
View
function SaveGame() {
if ('@Session["Username"]' == '@Model.Player1.Username') {
p1 = true;
}
else {
p1 = false;
}
var characters = document.getElementsByClassName("char");
var chardata = ;
for (var i = 0; i < characters.length; i++) {
var id = characters[i].id;
var state = characters[i].classList[1];
chardata.push(id, state);
}
console.log(chardata);
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'GET',
data: JSON.stringify({ 'character': chardata }),
cache: false,
contentType: 'application/JSON',
success: function (result) {
alert("Game Saved");
}
});
}
Gamecontroller/SaveGame
public bool SaveGame(JsonDecode character)
{
ViewGame game = (ViewGame)TempData["game"];
TempData["game"] = game;
return true;
//return charLayer.SaveCharacters(game.Id, ids, states, isPlayer1);
}
character
will just be null
JsonDecode
public class JsonDecode
{
public object chardata { get; set; }
}
c# ajax asp.net-mvc
Create a view model representing the data you are sending and use that as the parameter.
– Shyju
Dec 27 '18 at 20:00
@Shyju if I do that both parameters are null
– Kevin Tinnemans
Dec 27 '18 at 20:09
No. As long as your property names matches the JS object names. It should work.
– Shyju
Dec 27 '18 at 20:10
@Shyju are you sure? I've updated my question to show you what I tried
– Kevin Tinnemans
Dec 27 '18 at 20:13
What is the data you are trying to send ? Where are you trying to send the bool value ? You are calling push with 2 values, which will send 2 values to the array!
– Shyju
Dec 27 '18 at 20:19
|
show 2 more comments
I've been trying to send an array of objects to a controller method using AJAX, but even after trying various methods I still won't get my desired result. This is my current code:
View
function SaveGame() {
if ('@Session["Username"]' == '@Model.Player1.Username') {
p1 = true;
}
else {
p1 = false;
}
var characters = document.getElementsByClassName("char");
var chardata = ;
for (var i = 0; i < characters.length; i++) {
var id = characters[i].id;
var state = characters[i].classList[1];
chardata.push(id, state);
}
console.log(chardata);
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'GET',
data: JSON.stringify({ 'character': chardata }),
cache: false,
contentType: 'application/JSON',
success: function (result) {
alert("Game Saved");
}
});
}
Gamecontroller/SaveGame
public bool SaveGame(JsonDecode character)
{
ViewGame game = (ViewGame)TempData["game"];
TempData["game"] = game;
return true;
//return charLayer.SaveCharacters(game.Id, ids, states, isPlayer1);
}
character
will just be null
JsonDecode
public class JsonDecode
{
public object chardata { get; set; }
}
c# ajax asp.net-mvc
I've been trying to send an array of objects to a controller method using AJAX, but even after trying various methods I still won't get my desired result. This is my current code:
View
function SaveGame() {
if ('@Session["Username"]' == '@Model.Player1.Username') {
p1 = true;
}
else {
p1 = false;
}
var characters = document.getElementsByClassName("char");
var chardata = ;
for (var i = 0; i < characters.length; i++) {
var id = characters[i].id;
var state = characters[i].classList[1];
chardata.push(id, state);
}
console.log(chardata);
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'GET',
data: JSON.stringify({ 'character': chardata }),
cache: false,
contentType: 'application/JSON',
success: function (result) {
alert("Game Saved");
}
});
}
Gamecontroller/SaveGame
public bool SaveGame(JsonDecode character)
{
ViewGame game = (ViewGame)TempData["game"];
TempData["game"] = game;
return true;
//return charLayer.SaveCharacters(game.Id, ids, states, isPlayer1);
}
character
will just be null
JsonDecode
public class JsonDecode
{
public object chardata { get; set; }
}
c# ajax asp.net-mvc
c# ajax asp.net-mvc
edited Dec 27 '18 at 20:13
asked Dec 27 '18 at 19:58
Kevin Tinnemans
414523
414523
Create a view model representing the data you are sending and use that as the parameter.
– Shyju
Dec 27 '18 at 20:00
@Shyju if I do that both parameters are null
– Kevin Tinnemans
Dec 27 '18 at 20:09
No. As long as your property names matches the JS object names. It should work.
– Shyju
Dec 27 '18 at 20:10
@Shyju are you sure? I've updated my question to show you what I tried
– Kevin Tinnemans
Dec 27 '18 at 20:13
What is the data you are trying to send ? Where are you trying to send the bool value ? You are calling push with 2 values, which will send 2 values to the array!
– Shyju
Dec 27 '18 at 20:19
|
show 2 more comments
Create a view model representing the data you are sending and use that as the parameter.
– Shyju
Dec 27 '18 at 20:00
@Shyju if I do that both parameters are null
– Kevin Tinnemans
Dec 27 '18 at 20:09
No. As long as your property names matches the JS object names. It should work.
– Shyju
Dec 27 '18 at 20:10
@Shyju are you sure? I've updated my question to show you what I tried
– Kevin Tinnemans
Dec 27 '18 at 20:13
What is the data you are trying to send ? Where are you trying to send the bool value ? You are calling push with 2 values, which will send 2 values to the array!
– Shyju
Dec 27 '18 at 20:19
Create a view model representing the data you are sending and use that as the parameter.
– Shyju
Dec 27 '18 at 20:00
Create a view model representing the data you are sending and use that as the parameter.
– Shyju
Dec 27 '18 at 20:00
@Shyju if I do that both parameters are null
– Kevin Tinnemans
Dec 27 '18 at 20:09
@Shyju if I do that both parameters are null
– Kevin Tinnemans
Dec 27 '18 at 20:09
No. As long as your property names matches the JS object names. It should work.
– Shyju
Dec 27 '18 at 20:10
No. As long as your property names matches the JS object names. It should work.
– Shyju
Dec 27 '18 at 20:10
@Shyju are you sure? I've updated my question to show you what I tried
– Kevin Tinnemans
Dec 27 '18 at 20:13
@Shyju are you sure? I've updated my question to show you what I tried
– Kevin Tinnemans
Dec 27 '18 at 20:13
What is the data you are trying to send ? Where are you trying to send the bool value ? You are calling push with 2 values, which will send 2 values to the array!
– Shyju
Dec 27 '18 at 20:19
What is the data you are trying to send ? Where are you trying to send the bool value ? You are calling push with 2 values, which will send 2 values to the array!
– Shyju
Dec 27 '18 at 20:19
|
show 2 more comments
1 Answer
1
active
oldest
votes
Your current code is using GET
as the type for the $.ajax call. jQuery ajax will issue a GET request to the endpoint with the data appended to the querystring of the URL it is making the call to. When you want to send simple values, it is fine, but when you want to send a complex object like what you want to send, you should use POST type.
Also, for model binding to work, the structure of the data should be similar to your view model structure and property names. Based on the data you want to send, looks like you need a view model like this.
public class GameStateVm
{
public int Id { set;get;}
public string State { set;get;}
}
public class SaveGameVm
{
public GameStateVm Character { set;get;}
public bool PFlag { set;get;}
}
which you can use as the parameter of your HttpPost action method.
[HttpPost]
public ActionResult SaveGame(SaveGameVm characters)
{
// I am simply returning the posted data as it is, for testing
// You may return a boolean value if you want that.
return Json(characters);
}
and now in your client side code, make sure your JS object has similar strucutre and property names.
// JS object with same structure as our SaveGameVm
var d = { PFlag: false, character:};
d.PFlag = true; // to do : Set the value based on your condition
// dummy code to add 2 items to the array.
// to do : replace with your code to populate the array
for (var i = 0; i < 2; i++) {
var id =i; // to do : replace hard coded values
var state = 'active';
d.character.push({ id: id, state: state});
}
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'POST',
data: JSON.stringify(d),
contentType: 'application/JSON',
success: function (result) {
console.log(result);
}
});
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53950250%2fajax-send-array-and-bool-to-controller-method%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your current code is using GET
as the type for the $.ajax call. jQuery ajax will issue a GET request to the endpoint with the data appended to the querystring of the URL it is making the call to. When you want to send simple values, it is fine, but when you want to send a complex object like what you want to send, you should use POST type.
Also, for model binding to work, the structure of the data should be similar to your view model structure and property names. Based on the data you want to send, looks like you need a view model like this.
public class GameStateVm
{
public int Id { set;get;}
public string State { set;get;}
}
public class SaveGameVm
{
public GameStateVm Character { set;get;}
public bool PFlag { set;get;}
}
which you can use as the parameter of your HttpPost action method.
[HttpPost]
public ActionResult SaveGame(SaveGameVm characters)
{
// I am simply returning the posted data as it is, for testing
// You may return a boolean value if you want that.
return Json(characters);
}
and now in your client side code, make sure your JS object has similar strucutre and property names.
// JS object with same structure as our SaveGameVm
var d = { PFlag: false, character:};
d.PFlag = true; // to do : Set the value based on your condition
// dummy code to add 2 items to the array.
// to do : replace with your code to populate the array
for (var i = 0; i < 2; i++) {
var id =i; // to do : replace hard coded values
var state = 'active';
d.character.push({ id: id, state: state});
}
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'POST',
data: JSON.stringify(d),
contentType: 'application/JSON',
success: function (result) {
console.log(result);
}
});
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
add a comment |
Your current code is using GET
as the type for the $.ajax call. jQuery ajax will issue a GET request to the endpoint with the data appended to the querystring of the URL it is making the call to. When you want to send simple values, it is fine, but when you want to send a complex object like what you want to send, you should use POST type.
Also, for model binding to work, the structure of the data should be similar to your view model structure and property names. Based on the data you want to send, looks like you need a view model like this.
public class GameStateVm
{
public int Id { set;get;}
public string State { set;get;}
}
public class SaveGameVm
{
public GameStateVm Character { set;get;}
public bool PFlag { set;get;}
}
which you can use as the parameter of your HttpPost action method.
[HttpPost]
public ActionResult SaveGame(SaveGameVm characters)
{
// I am simply returning the posted data as it is, for testing
// You may return a boolean value if you want that.
return Json(characters);
}
and now in your client side code, make sure your JS object has similar strucutre and property names.
// JS object with same structure as our SaveGameVm
var d = { PFlag: false, character:};
d.PFlag = true; // to do : Set the value based on your condition
// dummy code to add 2 items to the array.
// to do : replace with your code to populate the array
for (var i = 0; i < 2; i++) {
var id =i; // to do : replace hard coded values
var state = 'active';
d.character.push({ id: id, state: state});
}
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'POST',
data: JSON.stringify(d),
contentType: 'application/JSON',
success: function (result) {
console.log(result);
}
});
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
add a comment |
Your current code is using GET
as the type for the $.ajax call. jQuery ajax will issue a GET request to the endpoint with the data appended to the querystring of the URL it is making the call to. When you want to send simple values, it is fine, but when you want to send a complex object like what you want to send, you should use POST type.
Also, for model binding to work, the structure of the data should be similar to your view model structure and property names. Based on the data you want to send, looks like you need a view model like this.
public class GameStateVm
{
public int Id { set;get;}
public string State { set;get;}
}
public class SaveGameVm
{
public GameStateVm Character { set;get;}
public bool PFlag { set;get;}
}
which you can use as the parameter of your HttpPost action method.
[HttpPost]
public ActionResult SaveGame(SaveGameVm characters)
{
// I am simply returning the posted data as it is, for testing
// You may return a boolean value if you want that.
return Json(characters);
}
and now in your client side code, make sure your JS object has similar strucutre and property names.
// JS object with same structure as our SaveGameVm
var d = { PFlag: false, character:};
d.PFlag = true; // to do : Set the value based on your condition
// dummy code to add 2 items to the array.
// to do : replace with your code to populate the array
for (var i = 0; i < 2; i++) {
var id =i; // to do : replace hard coded values
var state = 'active';
d.character.push({ id: id, state: state});
}
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'POST',
data: JSON.stringify(d),
contentType: 'application/JSON',
success: function (result) {
console.log(result);
}
});
Your current code is using GET
as the type for the $.ajax call. jQuery ajax will issue a GET request to the endpoint with the data appended to the querystring of the URL it is making the call to. When you want to send simple values, it is fine, but when you want to send a complex object like what you want to send, you should use POST type.
Also, for model binding to work, the structure of the data should be similar to your view model structure and property names. Based on the data you want to send, looks like you need a view model like this.
public class GameStateVm
{
public int Id { set;get;}
public string State { set;get;}
}
public class SaveGameVm
{
public GameStateVm Character { set;get;}
public bool PFlag { set;get;}
}
which you can use as the parameter of your HttpPost action method.
[HttpPost]
public ActionResult SaveGame(SaveGameVm characters)
{
// I am simply returning the posted data as it is, for testing
// You may return a boolean value if you want that.
return Json(characters);
}
and now in your client side code, make sure your JS object has similar strucutre and property names.
// JS object with same structure as our SaveGameVm
var d = { PFlag: false, character:};
d.PFlag = true; // to do : Set the value based on your condition
// dummy code to add 2 items to the array.
// to do : replace with your code to populate the array
for (var i = 0; i < 2; i++) {
var id =i; // to do : replace hard coded values
var state = 'active';
d.character.push({ id: id, state: state});
}
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'POST',
data: JSON.stringify(d),
contentType: 'application/JSON',
success: function (result) {
console.log(result);
}
});
answered Dec 27 '18 at 20:30
Shyju
144k87330435
144k87330435
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
add a comment |
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
Yes this works, thank you for your patience
– Kevin Tinnemans
Dec 27 '18 at 20:44
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53950250%2fajax-send-array-and-bool-to-controller-method%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Create a view model representing the data you are sending and use that as the parameter.
– Shyju
Dec 27 '18 at 20:00
@Shyju if I do that both parameters are null
– Kevin Tinnemans
Dec 27 '18 at 20:09
No. As long as your property names matches the JS object names. It should work.
– Shyju
Dec 27 '18 at 20:10
@Shyju are you sure? I've updated my question to show you what I tried
– Kevin Tinnemans
Dec 27 '18 at 20:13
What is the data you are trying to send ? Where are you trying to send the bool value ? You are calling push with 2 values, which will send 2 values to the array!
– Shyju
Dec 27 '18 at 20:19