JSON Object always return undefined with AJAX - javascript

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

Related

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

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

Pass an array as parameter to a controller from an ajax call in JavaScript

I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database.
I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :
JSON primitive invalid
Null reference
Here's my function in my script (I don't know if my array's format is valid) :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Then, the POST call the following function in my controller :
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
Update 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.
If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :
[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}
Update :
Your javascript code should be :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}
Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).
To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);
Try changing your ajax data to something like this..
data : JSON.stringify({'docsToDelete':docsArray}),
Make these changes to your code.
In Jquery
data: docsArray, no need to stringify the array
In Controller
[Authorize] //remove [WebMethod]
public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
{
int id;
string[] arrayDocs = docsToDelete; //no need of deserilization
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json(id); //return id back to ajax call...
}

Cant get array from ajax

I have asp.net application where need to implement autocomplete, I try to load list of names from server side and then deserealize it in js code, but have an 500 error, can anybody help me?
Unknown web method GetListofCompanies.
Parameter name: methodName
Code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetListofCompanies(string name) {
var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
JS:
var name = "";
$.ajax({
url: "Company.aspx/GetListofCompanies",
type: "post",
data: { name: name },
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
$("#txtName").autocomplete({
source: responseArray
});
}
});
// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;
[WebMethod]
public static string GetListofCompanies(string name)
{
List<string> companies = new List<string>();
companies.Add("Company1");
companies.Add("Company2");
companies.Add("Company3");
companies.Add("Company4");
companies.Add("Company5");
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
// JS
function request() {
var name = "";
var data = { name: name };
$.ajax({
url: "Default.aspx/GetListofCompanies",
type: "POST",
contentType: 'application/json',
data: JSON.stringify(data)
}).success(function (data) {
// do your stuff here
})
.fail(function (e) {
alert("Error");
});
}

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

building, sending, and deserializing a json object that contains arrays

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);
}

Categories