is there a way to pass an array of object and then assign it to model?
i searched that making the same variable name in your model and object will do the work but it doesn't work for me.
the model always get null values.
var answers = [];
var answerOthers = [];
var comment = $("#message").val();
$("input:radio:checked").each(function () {
var questno = $(this).attr("data-question");
var ansid = $(this).val();
answers.push({ QUESTIONID: questno, ANSWERID: ansid});
if ($(this).val() == 3)
{
var txtOther = $("#otherTxt-" + $(this).attr("data-question")).val();
answerOthers.push({
QUESTIONID: questno,
ANSWER: txtOther
});
}
});
$.ajax({
url: 'insertQuestions',
data: { answers: answers, answer_others: answerOthers, userid: userid , comment: comment },
method: 'GET',
success: function ()
{
alert("saved");
},
error: function (e)
{
console.log(e);
}
});
c# controller
public void insertQuestions(List<ratingsModel.ANSWERS> answers,
List<ratingsModel.ANSWERS_OTHERS> answer_others, int userid , string comment)
{
insertAnswers(answers,userid);
insertAnswer_others(answer_others, userid);
MySqlConnection myconn2 = new MySqlConnection(cmn.connstring);
myconn2.Open();
string query3 = "INSERT INTO comments (userid,comment) VALUES" +
" (#userid,#comment)";
MySqlCommand cmd2 = new MySqlCommand(query3, myconn2);
cmd2.Parameters.AddWithValue("#userid", userid);
cmd2.Parameters.AddWithValue("#comment", comment);
cmd2.ExecuteNonQuery();
myconn2.Close();
}
You cannot do that with a GET (the data you pass to the method would need to be a query string and to represent your collections you need individual name/value pairs with collection indexers, for example
data { [0].QUESTIONID: xx, [0].ANSWERID: yy [1].QUESTIONID: zz, .... etc }
But it should not be a GET in any case. Your method is changing data so it should be a POST (and in addition, if your collections were large, your would exceed the query string limit and throw an exception)
Change the ajax code to
$.ajax({
url: #Url.Action('insertQuestions'), // dont hard code your url's
data: JSON.stringify({ answers: answers, answer_others: answerOthers, userid: userid, comment: comment }) // modify,
contentType: 'application/json', // add
method: 'POST', // change
success: function() {
....
As a side note, if you had generated your form correctly using the strongly typed HtmlHelper methods, then you code could simply have been
$.ajax({
url: #Url.Action('insertQuestions'),
data: $('form').serialize(),
method: 'POST',
success: function() {
....
and none of the code for generating the arrays would be required.
Related
I have the following associative array and i try to send it to the server via AJAX.
Checking my console, in the network tab, it's posted but nothing is parsed.
Array creation:
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
Assoc array (console.log):
[category: "6", Type1: "998", Type2: "20100100"]
Request:
$.ajax({
type: POST,
url: 'something.php',
data: {
data: FiltersArray
}
}).done(function(data) {
console.log('Server Response: ' + data);
})
Complete code:
$(document).ready(function() {
var filters = {
category: $("#categoryInp"),
type1: $("#type1Inp"),
type2: $("#type2Inp"),
button: $("#FilterBtn"),
returnArray: function() {
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
return FiltersArray;
},
sendRequest: function(type, URL) {
$.ajax({
type: type,
url: URL,
data: JSON.stringify(this.returnArray()),
beforeSend: function() {}
}).done(function(data) {
console.log('Server Response: ' + data);
}).fail(function() {
alert("An error occurred!");
});
}
};
filters.button.on('click', e => {
console.log(filters.returnArray());
filters.sendRequest('POST', 'Modules/Products.order.module.php');
});
});
There is no such thing as an associative array in JavaScript.
There are objects, which hold key:value pairs of data.
There are arrays, which are a type of object that provides special behaviour when the key name is an integer.
jQuery distinguishes between arrays and other kinds of objects when you pass one in data.
If you pass an array it will not do anything with key:value pairs where the key is not an integer.
Use a plain object and not an array for this.
Aside: Variable names beginning with a capital letter are traditionally reserved for storing constructor functions in JavaScript. Don't use that naming convention for other kinds of data.
var filters = {};
filters['category'] = this.category.val();
filters['Type1'] = this.type1.val();
filters['Type2'] = this.type2.val();
It would be easier to just collect all the data as you create the object though:
var filters = {
category: this.category.val(),
Type1: this.type1.val(),
Type2: this.type2.val()
};
Aside
data: {
data: FiltersArray
}
This will create a (seemingly pointlessly) complex data structure that you'll need to access in PHP as $_POST['data']['category'].
You probably want just:
data: filters
Aside
data: JSON.stringify(this.returnArray()),
This will send JSON instead of form encoded data.
If you do that then you'll also need to:
Set the contentType of the request to indicate that you are sending JSON
Explicitly parse the JSON in PHP
So you probably don't want to do that.
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept
I need to populate the ajax data attribute with one or many key value pairs to post up to a MVC controller action. The snag is that I want to use one js function to send data to different controller actions each with different signatures. Here goes:
MVC View
#{
var Params = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("param1","foo"),
new KeyValuePair<string, string>("param2","bar"),
};
var targetUrl = "/MyActionName/";
var myParams = #Json.Encode(Params);
var clickFunction = $"myFunction('{targetUrl}', {myParams})";
}
Do It
Javascript function
function myFunction(url, paramData) {
var dataParams = [];
paramData.forEach(function (arrayItem) {
var key = arrayItem.Key;
var value = arrayItem.Value;
dataParams[key] = value;
});
// This works
$.ajax({
url: url,
data: {
param1: "foo",
param2: "bar"
},
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
// This doesn't
$.ajax({
url: url,
data: { dataParams },
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
}
Controller Action Example 1
public PartialViewResult MyAction1(string param1, string param2)
{
....
}
Controller Action Example 2
public PartialViewResult MyAction2(string apple, string orange, string grape)
{
....
}
Controller Action Example 3
public PartialViewResult MyAction3(string pig, string cow, string dog, string cat)
{
....
}
I'd like myFunction to be used to post up to multiple controller actions with varying signatures. So i'd just need to throw a list of KeyValuePair at myFunction and will handle it.
Tried so far without any luck:
using JSON.stringify but is doesn't format dataParams in the correct way.
using a MVC model instead of many separate params. This is because the param names will be different so one model won't fit all scenarios
If I can get this to work i'd then extend it to handle data types other than string but for sake of simplicity i've stuck to string here
Any help would be very much appreciated
It is wrong dataParams you must to set is as an object
function myFunction(url, paramData) {
var dataParams = {};
paramData.forEach(function (arrayItem) {
var key = arrayItem.Key;
var value = arrayItem.Value;
dataParams[key] = value;
});
// This works
$.ajax({
url: url,
data: {
param1: "foo",
param2: "bar"
},
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
// This doesn't
$.ajax({
url: url,
data: dataParams,
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
}
I'm reaaallly new at JSON, but here's what I got. I needed to create an object that contains an array/list and a couple flat fields. For example:
var names= new Array();
names[0] = "Christy";
names[1] = "Jeremy";
var obj = {
names: names,
age: "21+",
comment: "friends"
};
I then stringify it and attempt to send it to a pagemethod via AJAX:
var jsonData = JSON.stringify(obj);
sendData(obj);
And then the send:
function sendData(jsonData) {
$.ajax({
type: "POST",
url: "Default.aspx/TestArray",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('win');
},
error: function (a, b, ex) {
alert('fail');
}
});
}
so all together:
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var names = new Array();
names[0] = "Christy";
names[1] = "Jeremy";
var obj = {
names: names,
age: "21+",
comment: "friends"
};
var jsonData = JSON.stringify(obj);
sendData(jsonData);
});
function sendData(jsonData) {
$.ajax({
type: "POST",
url: "Default.aspx/TestArray",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (a, b, ex) {
alert("oops: " + ex);
}
});
}
});
I'm not sure if I'm doing this right. It doesn't even get to the webmethod, rather it goes straight to the error function. But just for the sake of conversation, this is what I have in the codebehind:
[WebMethod()]
public static string TestArray(string guids)
{
Comment cmt = (Comment)JsonConvert.DeserializeObject(guids, typeof(Comment));
return "Winner";
}
And of course class im trying to deserialize into:
public class Comment
{
public List<string> names { get; set; }
public string age { get; set; }
public string comment { get; set; }
}
According to the signature of your web method:
public static string TestArray(string guids)
you must send a single string argument whereas you are sending an entire complex JSON object which doesn't match. So:
var jsonData = JSON.stringify({ guids: 'foo bar' });
Now if you wanted to send a complex structure use:
public static string TestArray(Comment comment)
and then:
var names = new Array();
names[0] = "Christy";
names[1] = "Jeremy";
var obj = {
names: names,
age: "21+",
comment: "friends"
};
var jsonData = JSON.stringify({ comment: obj });
Also inside your web method don't do any JSON serialization/deserializations. That's infrastructure stuff that's handled for you by the framework. So to recap:
[WebMethod]
public static string TestArray(Comment comment)
{
return "Winner";
}
and then:
var names = new Array();
names[0] = "Christy";
names[1] = "Jeremy";
var obj = {
names: names,
age: "21+",
comment: "friends"
};
var jsonData = JSON.stringify({ comment: obj });
$.ajax({
type: "POST",
url: "Default.aspx/TestArray",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Notice the .d property. That's ASP.NET PageMethods
// serialize the response.
alert(msg.d);
},
error: function (a, b, ex) {
alert('fail');
}
});
Also in order to be able to easily debug such problems in the future I would very strongly recommend you using a javascript debugging tool such as FireBug which shows you any potential js errors that you might have as well as all network traffic including AJAX requests.
You're json data object does not have to be Stringified. JQuery automatically creates a json object for it:
var jsonData = JSON.stringify(obj);
sendData(jsonData);
Can become:
sendData(obj);
Also, in code behind you use JsonConvert from the JSON.Net library, .NET also has a (somewhat limited) JSON parser called JavaScriptSerializer. That way you can use something like:
public static string TestArray(string guids)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Deserialize
Comment cmt = serializer.Deserialize<Comment>(guids);
}