Cant get array from ajax - javascript

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

Related

application/json content type store location

the result of content type : "application/x-www-form-urlencoded" stored in Request.Form in Asp MVC.
but for "application/json" i cant find the store location
here is the code that i use:
ajax part
// reading form data
var form = $("form")[0];
var formData = new FormData(form);
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var data = JSON.stringify(object);
// ajax part
// POST application/json; charset=utf-8
$.ajax({
type: "POST",
url: "#Url.Action("FormSubmit","Home")",
data: data,
dataType: "json",
async: true,
contentType: "application/json",
processData: true,
success: function(result) { },
error: function(result) { }
});
Controller Part
[HttpPost]
public ActionResult FormSubmit(string input1, string input2)
{
var httpContext= HttpContext;
var response = Response;
var request = Request;
throw new NotImplementedException();
}
You can use controller like this:
[HttpPost]
public ActionResult SomeAction(string data)
{
List<YOUR_MODEL_CLASS> payloadObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YOUR_MODEL_CLASS>>(data)(modelData);
// process your data
}
Found the answer
i just need to read post Payload
here is the code
[HttpPost]
public ActionResult FormSubmit()
{
Request.InputStream.Position = 0;
var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength));
string reqString = Encoding.ASCII.GetString(reqMemStream.ToArray());
throw new NotImplementedException();
}

JSON Object always return undefined with AJAX

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

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>

Why ModelBinding don't work with FormData but works with RequestPayload?

I have been working with Web API and found an interesting observation that I am not able to understand.
controller:
public class UserController: ApiController
{
public void Post(MyViewModel data)
{
//data is null here if pass in FormData but available if its sent through Request Payload
}
}
viewModel
public class MyViewModel{
public long SenderId { get; set; }
public string MessageText { get; set; }
public long[] Receivers { get; set; }
}
JS that is not working
var usr = {};
usr.SenderId = "10";
usr.MessageText = "test message";
usr.Receivers = new Array();
usr.Receivers.push("4");
usr.Receivers.push("5");
usr.Receivers.push("6");
$.ajax(
{
url: '/api/User',
type: 'POST',
data: JSON.stringify(usr),
success: function(response) { debugger; },
error: function(error) {debugger;}
});
JS that is working
var usr = {};
usr.SenderId = "10";
usr.MessageText = "test message";
usr.Receivers = new Array();
usr.Receivers.push("4");
usr.Receivers.push("5");
usr.Receivers.push("6");
$.post( "/api/User", usr)
.done(function( data ) {
debugger;
});
So, if I pass on $.ajax with lots of other configuration like type, contentType, accept etc, it still don't bind model correctly but in case of $.post it works.
Can anybody explain WHY?
Try looking at what gets POSTed when you try it with $.ajax (e.g. with Fiddler of F12 tools of your choice). It can very well be that jQuery passes the data as URL-encoded string rather that as JSON literal.
To fix the issue try specifying dataType together with contentType parameter. Also, I don't think you need JSON.stringify, just pass the JSON literal you're creating:
$.ajax({
data: usr,
dataType: 'json',
contentType: 'application/json',
/* The rest of your configuration. */
});
Here's the TypeScript method that we use in one of our projects (ko.toJSON returns a string representing a JSON literal passed as a method parameter):
public static callApi(url: string, type?: string, data?: any): RSVP.Promise {
return new RSVP.Promise((resolve, reject) => {
$.ajax('/api/' + url, {
type: type || 'get',
data: data != null ? ko.toJSON(data) : null,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: () => {
resolve.apply(this, arguments);
},
error: () => {
reject.apply(this, arguments);
}
});
});
}
Hope this helps.

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