I have defined a webMethod in code behind as follows.
[System.Web.Services.WebMethod]
public static string testCall(int qid, String answerContent)
{
log.Debug("this is call from jquery" + qid.ToString() + answerContent);
return "true";
}
I am trying to call this method via ajax call in jquery as below.
<script>
$(".submitBtn").click(function (e) {
alert(this.id);
var qID = this.id;
$.ajax({
type: "POST",
url: '/default.aspx/testCall',
data: '{ "qid":' + qID + ', "answerContent":"test" }',
contentType: "application/json; charset=utf-8",
success: function () {
},
failure: function (response) {
alert("fail");
},
dataType: 'html'
});
});
</script>
But this is not working.
However is I pass hardcoded values for parameters as below, it works fine.
data: '{ "qid":"1234", "answerContent":"test" }'
But with var qID passing as parameter not working
Don't hand-assemble JSON. You will get bitten by characters you don't expect in strings, you'll miss out delimiters, etc.
Instead, use the JSON stringifier:
data: JSON.stringify({qid: qID, answerContent:"test"}),
If the ID value is really a number (you're receiving it as an int), you'll want to parse it (as this.id is a string):
data: JSON.stringify({qid: +qID, answerContent:"test"}),
// ------------------------^
...but your hardcoded example that you said works uses a string for the ID, so...
You should use this line as:
data: '{ "qid": "' + qID + '", "answerContent":"test" }'
Related
I have a dataset with location-data. And in the GetLocation the data are transformed in a latitude and longitude value. That works fine. But when I returned to the html-page. The data is undefined. What is the reason? And how can I resolve this with JSon-data?
[HttpGet]
public JsonResult GetLocation(Dictionary<string, string> items)
{
var result = "{ 'latitude': '" + latitude + "', 'longitude': '" + longitude + "'}";
return Json(result);
}
in the html:
if (item.Location == null) {
$.ajax({
url: "#Url.Action("GetLocation", "Home")",
dataType: "json",
data: { items: item },
type: "GET",
success: (function (data) {
location = JSON.parse(data);
})
});
console.log("location:");
console.log(location);
You are double-encoding the JSON here. The Json() function in the action method is encoding the string as JSON, which means the Javascript will be receiving something like this (note the quotes around the entire thing):
"{ 'latitude': '50.69093', 'longitude': '4.337744'}"
You should instead do something like this:
return Json(new { latitude, longitude }, JsonRequestBehavior.AllowGet);
Now in your success function, you will be able to access the values:
success: (function (data) {
location = JSON.parse(data);
console.log(location.latitude);
})
Note also the addition of JsonRequestBehavior.AllowGet, see here for why that is needed.
Please change like below
in MVC return type:
return Json(new { result = result }, JsonRequestBehavior.AllowGet);
in JQuery AJAX
location = JSON.parse(data.result);
I have the following example:
var url = '#Url.Action("GetProgData", "Prog")' + '?lbId=' + labId;
$("#loginList").jqGrid({
url: url,
datatype: "json",
colNames: ['PNum', 'Client', 'Salesperson', 'Email'],
colModel: [ ...
......
The method looks like the following in c# MVC:
public JsonResult GetLoginData(int rows, int page, string sidx, string sord, string searchField, string searchString, string searchOper, int? labId)
What I like to do is to pass the value of labId conditionally so I have the following but doesn't seem to pass labId as it return null:
$("#LabId").change(function () {
labId = $("#LabId").val();
setupGrid(labId);
$("#loginList").trigger("reloadGrid", [{ page: 1}]);
});
Not sure when I do it in the .change of a dropdown the value of labID does't go through fine
I think that you can sent null as the value of labId if
$("#loginList").jqGrid({
url: '#Url.Action("GetProgData", "Prog")',
postData: {
lId: function () {
var labId = $("#LabId").val();
return labId === "" ? null : labId;
}
},
datatype: "json",
colNames: ['PNum', 'Client', 'Salesperson', 'Email',
...
});
If the above solution will not work, than you can do the following alternatively
$("#loginList").jqGrid({
url: '#Url.Action("GetProgData", "Prog")',
serializeGridData: function (data) {
var labId = $("#LabId").val();
return labId === "" ? data : $.extend(true, {}, data, {lId: labId});
},
datatype: "json",
colNames: ['PNum', 'Client', 'Salesperson', 'Email',
...
});
I'm getting started with WebAPI and for the most part all is going well. I'm running into a problem with one particular function. This one differs from the other because it's only parameter is of type IEnumerable.
I've set a breakpoint on the first line of the Post() function and I'm hitting the function but the "values" parameter ALWAYS has a count of 0. I verified that the parameter going in on the client side does, in fact, contain an array of integers. If I remove the [FromUri] attribute, the 'values' parameter is NULL instead of a count of 0.
How do I get my array of integers to come through on my WebAPI function?
Here's the WebAPI function:
[System.Web.Mvc.HttpPost]
public void Post([FromUri] IEnumerable<int> values)
{
if (values == null || !values.Any()) return;
int sortorder = 1;
foreach (int photoId in values)
{
_horseRepository.UpdateSortOrder(photoId, sortorder);
sortorder++;
}
}
Here's the AJAX call (this is using the jQuery UI Sortable feature):
$(".sortable").sortable({
update: function (event, ui) {
var newArray = $(".sortable").sortable("toArray");
$.ajax({
url: '/api/photo',
type: 'POST',
contentType: 'application/json, charset=utf-8',
async: true,
dataType: 'json',
data: JSON.stringify(newArray),
complete: function (data) { }
});
}
});
contentType: 'application/json, charset=utf-8',
should become (the separator between the content type and the charset is a semicolon, not a comma):
contentType: 'application/json; charset=utf-8',
and:
public void Post([FromUri] IEnumerable<int> values)
should become (there are no Uri parameters in a POST request):
public void Post(IEnumerable<int> values)
Now you are good to go assuming that newArray (which you haven't shown here) is an array of integers:
newArray = [ 1, 2, 3 ]
In my static web method I populate a dictionary with the Bankid and Bankname that I select from a database. The Id goes to the Key and the Value goes to the value part. SO there're approximately 20 key-value-pairs in my dictionary. Then I return this dictionary to my ajax call:
$.ajax({
type: 'POST',
url: 'AJAX.aspx/Banks',
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$.each(data.d, function ()
{
$("#testDiv").append(this.Key + " " +this.Value + "<br/>");
});
},
error: function (x, e)
{
alert("The call to the server side failed. " + x.responseText);
}
});
In the above case I get 20 rows of undefined undefined. But if I remove both .Key and .Value from this I just get the value, so bank names. I need both the key and the value because I'm going to populate a select element with them-key for value and the value for inner html.
In case you want to see my webmethod, here it is:
[WebMethod]
public static Dictionary<string, string> Banks()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
DatabaseProvider provider = GetDatabaseProvider();
provider.AddOutParameter("V_CUR", OracleType.RefCursor);
DataTable dt=provider.SelectDataTable("AGAPUS.PAYMENT.SP_BANKS", CommandType.StoredProcedure);
foreach (DataRow row in dt.Rows)
{
dict.Add(row["PAYMENTTYPE"].ToString(), row["PAYMENTTYPEID"].ToString());
}
return dict;
}
Looks more like a question about jQuery to me. That said, try changing your success function to:
success: function (data)
{
$.each(data.d, function ( key, value )
{
$("#testDiv").append(key + " " + value + "<br/>");
});
}
The key and value are passed as parameters to the function when evaluating a map.
I have controller
var subCategories = m_listsRepository.GetSubCategories(id);
var items = subCategories.Select(x=>new MyDataNameAndId(){Id = x.Value, Name = x.Text});
return Json(items);
And ajax:
$.ajax({
url: urlString,
type: 'POST',
data: JSON.stringify({ id: districtId }),
dataType: 'json',
contentType: 'application/json',
cache: 'false',
success: function (data) {
alert("success");
$.each(data, function (key, MyDataNameAndId) {
alert(key);//== 0
alert(MyDataNameAndId);// then throws
$('select#ChangeOnsubCategoryId').append('<option value="0">Select One</option>');
$.each(MyDataNameAndId, function (index, manager) {
$('select#ChangeOnsubCategoryId').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
});
}
});
what am I doing wrong?
UPDATE:
Controller is worked.
alert("success"); - is show
alert(key); - is show 0
alert(MyDataNameAndId); - not show.
I need generate in 'select#ChangeOnsubCategoryId' options from select#ChangeOnsubCategoryId
How do this? this understand?
I do not know how to show what passed json
json string:
[{"Id":"53","Name":"футбол"}]
From the JSON output you've written out, I'd rewrite it a little bit like this:
$.ajax({
url: urlString,
type: 'POST',
data: JSON.stringify({ id: districtId }),
dataType: 'json',
contentType: 'application/json',
cache: 'false',
success: function (data) {
if (!data) return; // if data is empty, return
var $select = $('select#ChangeOnsubCategoryId');
// put the select element in a variable so you don't need to
// jquery select it again
$select.append('<option value="0">Select One</option>');
// I guess you first want to add a "select one" option
// data should be an array e.g. [{"Id":"53","Name":"футбол"}]
$.each(data, function (key, manager) {
// for each "manager" in the "data" array
// manager should be an object in the data
// array e.g. {"Id":"53","Name":"футбол"}
// no need to for each it
$select.append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
// add the manager in the select box
});
}
});
I'm assuming stuff though. Use a javascript debugger (such as developer tools in Chrome or Firebug in Firefox) to check what values you get from the ajax call. Put the breakpoint inside the function and then watch what the data becomes (in this case it should be an array of objects containing Id and Name).
$.each(MyDataNameAndId, function (index, manager) {
$('select#ChangeOnsubCategoryId').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
should be just
$('select#ChangeOnsubCategoryId').append(
'<option value="' + MyDataNameAndId.Id + '">'
+ MyDataNameAndId.Name +
'</option>');
The sample code works for me without exceptions which leads me to believe there's something wrong with the JSON being returned. Check that it actually returns the string you posted.