Returning Json Format response from c# - c#

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

Related

jQuery Array is not posting to ASP.NET MVC controller

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

Error JSON.parse with JQuery Autocomplete ASP.Net MVC

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.

The parameters dictionary contains a null entry for parameter (ASP.NET)

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

ASP.NET Web Service JSON Arrays

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.

Switching from POST to GET for jqGrid populated from WCF back-end

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.

Categories

Resources