I need some help with my web service and json call.. stuck trying to get the data returned, I've done this successful with strings and objects.. but not an array...
My Web Service Contains:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSearchCriteria()
{
var js = new JavaScriptSerializer();
var obj = HttpContext.Current.Session["mysessionname"];
if (obj == null)
{
var result = new Criteria[]
{
new Criteria() { Key = Guid.NewGuid(), Operator = "=", ColumnName = "CheckID", Value = "" }
};
var serial = js.Serialize(result);
return serial;
}
else
{
var serial = js.Serialize((Criteria[])obj);
return serial;
}
}
Criteria is:
[Serializable]
public class Criteria
{
public Guid Key { get; set; }
public string ColumnName { get; set; }
public string Operator { get; set; }
public string Value { get; set; }
}
My Page Contains:
<script type="text/javascript">
function RefreshCriteria() {
$.ajax({
type: 'POST',
url: '<%= System.Web.VirtualPathUtility.ToAbsolute("~/Services/WebService.asmx/GetSearchCriteria") %>',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
success: function (data) {
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
}
});
}
$(document).ready(function () {
RefreshCriteria();
});
</script>
What I'm getting is undefined every time.. tried doing
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
$(data).each(function (i, obj) {
alert(obj);
});
$(data).each(function (i) {
alert(this);
});
None worked so far..
you can tighten up the ajax
$.ajax({
type: 'POST',
url: '*you need a url here*',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
console.log(item);
});
}
});
next using either firebug or fiddler monitor the request/response to ensure what you are sending and receiving is what you expected.
Related
I am having a hard time posting a list of arrays from my view to the controller. Every other value is coming through.
Can someone spot what is wrong with my code?
Controller:
public ActionResult SaveProgress(BBCRMSurveyVM model)
{
try
{
return Json(new { success = true });
}
catch (Exception e)
{
return Json(new { success = false, msg = e.Message });
}
}
Main view model:
public string ImplementationProcessFeelWasSuccessful { get; set; }
public string ImplementationProcessAdviceOtherFederations { get; set; }
public List<AdditionalTechnologyVM> AdditionalTech = new List<AdditionalTechnologyVM>();
AdditionalTechVM:
public class AdditionalTechnologyVM
{
public string PlatformName { get; set; }
public string BusinessPurpose { get; set; }
public bool? FullyIntergrated { get; set; }
public bool? PartiallyIntergrated { get; set; }
}
JS file:
function onAddButtonClickEvent() {
additionaltechs.push({
'PlatformName': platformNameAT,
'BusinessPurpose': businessPurposeAT,
'FullyIntergrated': intergrated == "Fully" ? true : false,
'PartiallyIntergrated': intergrated == "Partially" ? true : false
});
}
function SaveProgress() {
var formData = $('#wizard').serializeArray();
//if (additionaltechs.length > 0) {
// for (var x = 0; x < additionaltechs.length; x++) {
// formData[formData.length] = { name: "AdditionalTech", value: JSON.stringify(additionaltechs[x]) };
// }
//}
formData[formData.length] = { name: "AdditionalTech", value: additionaltechs };
$.each(formData, function (index, field) {
if (field.name.search('Budget') > 0) {
field.value = field.value.replace('$', '').replace(/,/g, '');
}
});
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
The output in the console:
The list count is always 0?
I think you made this more complicated than you needed it to be. :)
Ultimately, it looks like your controller method is taking a single model, not an array. Thus, I would suspect to see the JSON you send look like this:
{
"ImplementationProcessFeelWasSuccessful" : "",
"ImplementationProcessAdviceOtherFederations" : "",
"AdditionalTech" : [...]
}
If it should be a single item being sent, then I'd expect your code to be like this:
function SaveProgress() {
var formData =
{
ImplementationProcessFeelWasSuccessful : $('#wizard #val1').val(),
ImplementationProcessAdviceOtherFederations : $('#wizard #val2').val(),
AdditionalTech : additionaltechs
};
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
However, you are sending an array of items up and that makes no sense here.
Ended up sending the list as a JSON string & receiving it also as a string. In the controller I using the JsonConvert.DeserializeObject method like this:
var additionalTechs = JsonConvert.DeserializeObject<List<AdditionalTechnologyVM>>
(model.AdditionalTech);
I am passing multiple parameters in an object and then passing it to a Method in the controller. It is hitting the method but it's not carrying the data to be sent from ajax call to the method . When I am going to check object of the model it displays null. SO can I send the data in such a way or should I try another approach?
Thanks in advance Please help me.
Here is my code.
var Color = [], Material = [], Size = [], FinishingType = [], Style = [];
$('.productFilterLabelList .filterList').on('change', '[type=checkbox]', function () {
debugger;
var Main = {};
var filterType = $(this).parents('.productFilterLabelList').find('.hdn-filter-type').val();
var filterTypeID = $(this).val();
var ischeked = $(this).is(':checked');
if (ischeked) {
if (filterType == 'color') {
Color.push(filterTypeID);
}
else if (filterType == 'size') {
Size.push(filterTypeID);
}
else if (filterType == 'finsih') {
FinishingType.push(filterTypeID);
}
else if (filterType == 'material') {
Material.push(filterTypeID)
}
else {
Style.push(filterTypeID);
}
}
else {
alert('hello');
if (filterType == 'color') {
Color.pop(filterTypeID);
}
else if (filterType == 'size') {
Size.pop(filterTypeID);
}
else if (filterType == 'finsih') {
FinishingType.pop(filterTypeID);
}
else if (filterType == 'material') {
Material.pop(filterTypeID)
}
else {
Style.pop(filterTypeID);
}
}
Main = {
Color: Color,
Size: Size,
FinishingType: FinishingType,
Material: Material,
Style: Style
}
console.log(Main);
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
data: '{Main:' +JSON.stringify(Main)+' }',
success: function (results) {
}
})
});
public ActionResult SearchByAllFilterTags(ProductFilterViewModel Main)
{
return Json("", JsonRequestBehavior.AllowGet);
}`public class ProductFilterViewModel
{
public int[] Color { get; set; }
public int[] Material { get; set; }
public int[] Size { get; set; }
public int[] FinishingType { get; set; }
public int[] Style { get; set; }
public int[] Pattern { get; set; }
//public string FilterText { get; set; }
//public List<ProductFilterViewModel> FilterTextList { get; set; }
}`
You don't need to stringify your object. Just pass your Main object:
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
traditional: true,
data: Main,
success: function (results) {
}
})
Edit:
If your arrays are empty in the action method try to add traditional: true to ajax settings
You do not need to stringify. Use this format:
Main = {
"Color": [{Color}],
"Size": [{Size}],
"FinishingType": [{FinishingType}],
"Material": [{Material}],
"Style": [{Style}]
}
console.log(Main);
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
data: Main,
success: function (results) {
}
})
});
As long as you didn't add quotation marks in your json data, your data will not pass.
This will work if your model at the controller is matched.
I have method to add data to db on Aajax request
Here is code on back-end
public ActionResult AddingInternalAppointment(string Start, string End, string Title, DateTime Date,int id)
{
using (var ctx = new ApplicationDbContext())
{
Appointment appointmentInt = new Appointment()
{
Start_appointment = Start,
End_appointment = End,
Title = Title,
Type_of_appointment = "Internal",
Date = Date
};
ctx.Appointments.Add(appointmentInt);
ctx.SaveChanges();
return Json(new {Result = "Success", Message = "Saved Successfully"});
}
}
And here is AJAX request on front - end:
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
},
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
When I call this function it show me this error, but I have values in Date.
How I can fix this?
Try changing parameter name Date to something else (like appointmentDate). You need to change same in ajax call.
A few things.
Create a model for the Action
public class AppointmentOptions {
public string Start { get; set;}
public string End { get; set;}
public string Title { get; set;}
public DateTime Date { get; set;}
public int Id { get; set;}
}
Update the action accordingly
[HttpPost]
public ActionResult AddingInternalAppointment([FromBody]AppointmentOptions model) {
if(ModelState.IsValid) {
string Start = model.Start;
string End = model.End;
//...
//...code removed for brevity
}
Next on the client update ajax call
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
var model = {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
};
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: JSON.stringify(model), //<-- NOTE
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
I need following json response from ajax call:
[{url:"http://localhost:63220/Images/heroAccent.png"},
{url:"http://localhost:63220/Images/heroAccent.png"}]
My ajax call is:
function loadtest() {
$.ajax({
type: 'GET',
url: '/Home/TestMethod',
async: true,
dataType:'json',
cache: false,
error: function () {
alert('Errror');
},
success: function (data) {
console.log(data);
}
});
}
My controller is:
public JsonResult TestMethod()
{
var items = new[] {
new {url = "http://localhost:63220/Images/heroAccent.png"},
new {url = "http://localhost:63220/Images/heroAccent.png"} };
return Json(items, JsonRequestBehavior.AllowGet);
}
It gives the response:
[{"url":"http://localhost:63220/Images/heroAccent.png"},
{"url":"http://localhost:63220/Images/heroAccent.png"}]
But I need following response. How can I get it?
[{url:"http://localhost:63220/Images/heroAccent.png"},
{url:"http://localhost:63220/Images/heroAccent.png"}]
You get the response you need in a JSON format. To convert it to an object, use :
JSON.parse(data);
You can use class.
var items = new List<Item>() { new Item() { url = "http://www.google.com" }, new Item() { url = "http://www.youtube.com" } };
return Json(items, JsonRequestBehavior.AllowGet);
Class
public class Item
{
public string Url { get; set; }
}
Result
I have an .aspx page that we are loading UserControls into dynamically at runtime. Each user control has some sort of textbox or combo or some other control. This all works fine. when we go to read the values out of the controls when the user presses search, we cannot do this directlly from C# code behind because the page does not know they are there. my solution is to read the values with JQuery and make an ajax call where I can set the values in a session variable for use when the user gets to the next page. I am having trouble with the JSon specifically.
I keep getting the error:
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":"
I find all the controls using .each and get the values for the JSon call:
function SaveFields() {
var data = [];
//get Search field criteria
$('[id^=Search_ucField_]').each(function (index, value) {
var field = $(this);
var id = $(this).attr('id').split("_")[2];
var fieldValue = $(this).val();
if (field.is('input')) {
var item = {};
item['FieldID'] = id;
item['Criteria'] = fieldValue;
item['IsActive'] = 1;
item['FieldCategoryID'] = '1';
item['ControlPath'] = '~/Controls/Search/TextBox.aspx';
item['CategoryID'] = 1;
data.push(item);
}
});
$.ajax({
url: '/Ajax/Ajax.aspx/DoSearch',
type: 'POST',
data: JSON.stringify(data),
datatype: 'json',
contentType: 'application/json',
success: function (msg) {
console.log(msg);
},
error: function (xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
}
Here is the object I am trying to deserialize into:
[DataContract]
public class SearchFields
{
[DataMember]
public List<SearchField> Field { get; set; }
}
[DataContract]
public class SearchField
{
[DataMember]
public string FieldID { get; set; }
[DataMember]
public bool IsActive { get; set; }
[DataMember]
public string Criteria { get; set; }
[DataMember]
public int FieldCategoryID { get; set; }
[DataMember]
public string ControlPath { get; set; }
}
Here is the WebMethod
[WebMethod]
public static string DoSearch(string Fields)
{
var sf = new SearchFields();
sf = JsonConvert.DeserializeObject<SearchFields>(Fields);
//save into session variable
SVars.NewUISearch.LastSearchFields = sf;
string x;
x = "until this works, this is a static response";
return x;
}
finally, here is a sample of the JSon that is being sent:
[{"FieldID":"52","getCriteria":"Bobs your uncle","IsActive":1,"FieldCategoryID":"1","ControlPath":"~/Controls/Search/TextBox.aspx"}]
Where am I going wrong here? Thanks in advance!
I couldn't get $('form').serialize() to work so this is what I did. Make sure the properties you define in model represent the properties in your model and are strongly typed.
var model = {
MyString: $("#MyString").val(),
MyNumber: $("#MyNumber").val(),
IsCheck: $("CHK").val()
};
$.ajax({
type: "POST",
url: "/Testing/Index",
contentType: "application/json",
data: JSON.stringify(model),
dataType: "json",
success: function (data) {
// Good stuff
},
error: function (data) {
// Bad stuff
}
})