I have a problem when I try to use the plugin Jquery Autocomplete. I am use ASP.Net C# and SQL for the BD.
The error is the follow:
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
I read into forums and say that it's for an invalid JSON format but I don't know how fix it or if it is the error.
My Model:
public class ListasAutocompletarModel
{
public int value { get; set; }
public string label { get; set; }
}
My Controller:
public JsonResult mostrarListaDatosMaestrosCodigo(string Codigo)
{
List<ListasAutocompletarModel> list = new List<ListasAutocompletarModel>();
try
{
DataTable datos = DM.mostrar_Lista_Codigo(Codigo);
foreach (DataRow data in datos.Rows)
{
list.Add(new ListasAutocompletarModel
{
value = Convert.ToInt32(data["ID"]),
label = data["Codigo"].ToString(),
});
}
}
catch (Exception e)
{
Classes.ErrorLogger.Registrar(this, e.ToString());
}
return Json(list,JsonRequestBehavior.AllowGet);
}
And my js:
$('#txtDatosMaestros_Codigo').autocomplete({
source: function (request, response) {
$.ajax({
url: "/DatosMaestros/mostrarListaDatosMaestrosCodigo",
type: "POST",
dataType: "json",
data: { Codigo: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.value };
}))
}
});
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
Please help me.
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 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.
I am trying to convert my client side ajax-call and jqGrid over to using GET instead of POST.
I've confirmed that the service is working as intended. Checked in firebug and inspected the JSON response object and it is correct -- however I am still missing something on the client side because the data isn't being populated into the grid. No specific javascript errors are showing up in firebug to speak of.
One question I have is how to approach the url/data parameters of the .ajax() request when using GET instead of POST. I don't really need to pass any parameters via the data parameter if I can just pass the parameters in the URL with a specific UriTemplate, I think?
function getData(pdata) {
var jqGridArgs = {
startDate: pdata.startDate(),
endDate: pdata.endDate()
};
var _url = "Service.svc/Products?s=" +
jqGridArgs.startDate + "&e=" + jqGridArgs.endDate;
$.ajax(
{
type: "GET",
contentType: "application/json; charset=utf-8",
url: _url,
//data: JSON.stringify({ args: jqGridArgs }), // do I need this for 'GET'?
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#jqGrid")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert('An error has occured retrieving data.');
}
});
}
And the grid code:
var start = page.queryitem('s');
var end = page.queryitem('e');
var columnModel = [
{ name: "ID", index: "ID", width: 175 },
{ name: "Name", index: "Name", width: 250 },
{ name: "Type", index: "Type", width: 250 }];
var columnNames = ['Product ID', 'Name', 'Type'];
$("#jqGrid").jqGrid({
postData:
{
startDate: function () { return start; },
endDate: function () { return end; },
},
datatype: function (pdata) {
getData(pdata); // calls the function above with 'postData'
},
colNames: columnNames,
colModel: columnModel,
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: false,
pagination: true,
pager: "#jqPager",
loadonce: true,
sortorder: "desc",
sortname: 'id',
cellEdit: false
});
And here is the back-end WCF method:
[WebGet( UriTemplate = "Products?s={start}&e={end}",
ResponseFormat = WebMessageFormat.Json)]
public JsonGridContract WebGetProducts(string start, string end)
{
DateTime _start = Convert.ToDateTime(start.ReplaceIf('T', ' '));
DateTime _end = Convert.ToDateTime(end.ReplaceIf('T', ' '));
var rows = GetProducts(_start, _end).Select(x => new
{
ID = x.ID,
Name = x.Name,
Type = x.Type
}).ToJson();
return new JsonGridContract() { records = rows.Count, total = rows.Count, page = 1, rows = rows };
}
This is how the data is encapsulated before going to the client:
[DataContract]
public class JsonGridContract
{
[DataContract]
public class JsonRow
{
[DataMember]
public int id { get; set; }
[DataMember]
public string[] cell { get; set; }
public JsonRow(int length)
{
cell = new string[length];
}
}
[DataMember]
public int page { get; set; }
[DataMember]
public int total { get; set; }
[DataMember]
public int records { get; set; }
[DataMember]
public List<JsonRow> rows { get; set; }
public JsonGridContract()
{
rows = new List<JsonRow>();
}
public JsonGridContract(List<JsonRow> _rows)
{
rows = _rows;
}
}
Try this:
var jqGridArgs = {
s: pdata.startDate(),
e: pdata.endDate()
};
var _url = "Service.svc/Products";
$.ajax(
{
type: "GET",
url: _url,
data: jqGridArgs,
dataType: "json",
success: function (data) {
var thegrid = $("#jqGrid")[0];
thegrid.addJSONData(data.d);
},
error: function (data, textStatus) {
alert('An error has occured retrieving data.');
}
});
No need to check for success, if the success function is being called, the operation was a success;
It also makes more since to use your javascript object to pass as data for a get. JQuery will automatically parse it and use it for query parameters.
Also, since its a get, and not a post, no need for content type.
Turns out the problem here was that there is no 'data.d' member when using GET. I am not sure why.
So changing,
thegrid.addJSONData(data.d)
to
thegrid.addJSONData(data)
fixed the problem.