I am working with the Bing Maps v8 API, trying to load my own GeoJSON onto a Bing Maps as in this example: https://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#geoJsonReadObject+JS
I am creating my JSON successfully (I have tested it using the Bing Maps Drag and Drop feature and all of my points show on the map. https://bingmapsv8samples.azurewebsites.net/#GeoJson%20Drag%20and%20Drop.
I am trying to get my GeoJSON to automatically load on a map, and I am receiving a JSON failure, and I am not sure why. (I am rather new to GeoJSON/JSON.)
Javascript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
var featureCollection = Microsoft.Maps.GeoJson.read(getGeoJson(), { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
function getGeoJson() {
$(function (callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
});
}
}
Controller:
[HttpPost]
public JsonResult PatGeoJSON(string parent)
{
JObject jsondata = JObject.FromObject(new
{
type = "FeatureCollection",
features = from p in pList
select new
{
type = "Feature",
geometry = new Geometry
{
type = "Point",
coordinates = new double?[] { p.GeoLocation.Longitude, p.GeoLocation.Latitude }
},
properties = new Properties
{
MemberName = p.MemberName,
/// etc...
}
}
});
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
My result is currently a "Failure" alert with the JSON string. Note: if I hardcode my GeoJSON as the result from the getGEOJSON function, all of my points show up on the map. Am I not reading the JsonResult correctly in my script?
Your getGeoJson function is asynchronous, so it doesn't return anything, this bing maps is receiving a null value to parse which it simply ignores and this no error. Specify a callback function when loading your geojson and when it responds, then read its value. Here is an updated version of your JavaScript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
getGeoJson(function(data){
var featureCollection = Microsoft.Maps.GeoJson.read(data, { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
});
function getGeoJson(callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
}
}
Related
I am trying to fetch company data based on company id through ajax and fill the related textboxes with the received data. Company id is selected through ajax autocomplete. The code was working fine two days back and suddenly it started generating an error for only first two entries of autocomplete and for rest it is working fine. Can anyone point out the mistake in this. Thank you.
Error Details: "Message":"A circular reference was detected while serializing an object of type \u0027System.Data.Entity.DynamicProxies.Company_81625299B5B4D7A3375D55E48BE84921728B8D48335366DF8CA6844A8D10FF5D\u0027.","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n.
Below is my code:
function setCompanyData(pageurl, txtboxid, txtResultid) {
var temp = true;
var searchTbox = $jq14("[id$=" + txtboxid + "]");
var resultTbox = $jq14("[id$=" + txtResultid + "]");
searchTbox.autocomplete({
source: function (request, response) {
$jq14.ajax({
url: pageurl,
data: "{ 'SearchText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('*')[0],
val: item.split('*')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoSelect: true,
autoFocus: true,
select: function (e, i) {
// e.preventDefault();
searchTbox.val(i.item.label);
resultTbox.val(i.item.val).trigger('change');
temp = true;
// return false;
},
change: function (e, i) {
var cId = resultTbox.val();
if (isEmptyOrSpaces(cId)) {
// error
cId = 0;
searchTbox.val("").trigger('');
}
if (isEmptyOrSpaces(searchTbox.val())) {
// error
cId = 0;
resultTbox.val("").trigger('change');
}
getCompanyDetails(cId);
},
minLength: 0
}).focus(function () {
if (temp) {
$jq14(this).autocomplete("search", "");
temp = false;
}
});
searchTbox.autocomplete("widget").addClass("fixedHeight");}
function getCompanyDetails(cid) {
$jq14.ajax({
url: "/sw/adm/update-delete-company.aspx/GetCompanyData",
data: "{ 'cId': '" + cid + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
$("#messageBox").hide().slideDown();
setTimeout(function () {
$("#messageBox").fadeOut();
}, 5000);
},
success: function (result) {
$jq14('#cphMainLeft_txtAddress').val(result.d.CompanyAddress);
$jq14('#cphMainLeft_txtCountry').val(result.d.CompanyCountry);
$jq14('#cphMainLeft_txtCity').val(result.d.CompanyCity);
$jq14('#cphMainLeft_txtNewCompanyName').val(result.d.CompanyName);
$jq14('#cphMainLeft_txtEmail').val(result.d.CompanyEmail);
$jq14('#cphMainLeft_txtPanNo').val(result.d.CompanyPAN);
$jq14('#cphMainLeft_txtTinNo').val(result.d.CompanyTIN);
$jq14('#cphMainLeft_txtPhone').val(result.d.CompanyPhone);
$jq14('#cphMainLeft_txtPincode').val(result.d.CompanyPincode);
$jq14('#cphMainLeft_hfTxtCountry').val(result.d.CompanyCountry);
$jq14("#cphMainLeft_ddlCompanyType").val(result.d.CompanyType);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
C# Webmethod goes like:
[WebMethod]
public static Company GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord != null)
return companyRecord;
else
return new Company();
}
Thank you Ashokkumar M. Prajapati for providing the hint.
Instead of returning Company object from [WebMethod], I have converted the company object to Json string in code behind and returned it.
Here is my WebMethod:
[WebMethod]
public static string GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord == null)
companyRecord = new Company();
string s = string.Empty;
s = JsonConvert.SerializeObject(companyRecord,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return s;
}
Then I updated the success method of getCompanyDetails(cid) to:
success: function (result) {
res = JSON.parse(result.d);
$jq14('#cphMainLeft_txtAddress').val(res['CompanyAddress']);
$jq14('#cphMainLeft_txtCountry').val(res['CompanyCountry']);
$jq14('#cphMainLeft_txtCity').val(res['CompanyCity']);
$jq14('#cphMainLeft_txtNewCompanyName').val(res['CompanyName']);
$jq14('#cphMainLeft_txtEmail').val(res['CompanyEmail']);
$jq14('#cphMainLeft_txtPanNo').val(res['CompanyPAN']);
$jq14('#cphMainLeft_txtTinNo').val(res['CompanyTIN']);
$jq14('#cphMainLeft_txtPhone').val(res['CompanyPhone']);
$jq14('#cphMainLeft_txtPincode').val(res['CompanyPincode']);
$jq14('#cphMainLeft_hfTxtCountry').val(res['CompanyCountry']);
$jq14("#cphMainLeft_ddlCompanyType").val(res['CompanyType']);
}
and it worked wonderfully. Thanks again.
Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});
I am using Fullcalendar plugin which is integrated with my ASP.NET MVC project. My main task consists of creating a schedule of reservations. I have written the code which is responsible for displaying events("Buttons") for specific date, and it works fine!. Code below:
var calendar = $("#calendar").fullCalendar({
weekends: false
, lang: 'pl',
header: {
left:'',
center: 'title',
right: 'today prev,next'
}, height: 630, week: true, columnFormat: 'dd M/D', minTime: '8:00', maxTime: '20:00', selectable: true,
allDaySlot: false, eventColor: '#F6A828',
events: function (start, end, timezone, callback) {
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
},
})
$('#calendar').fullCalendar('changeView', 'agendaWeek');
and method GetEvents in C#
public JsonResult GetEvents()
{
if (Session["DoctorID"] == null)
{
return Json(new { redirectUrl = Url.Action("Terminarz", "Recepcjonista"), isRedirect = true });
}
var listEvent = new List<CallendarEvent>();
List<CallendarEvent> list = TermRepository.GetAllEventsByDoctorId((int)Session["DoctorID"]);
int licznik = 1;
foreach (var item in list)
{
int count = Size(item.id, item.From, item.To);
for (int i = 0; i < count; i++)
{
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30)
});
licznik++;
}
}
var listEvent2 = from l in listEvent
select new
{
id = l.id,
//day = l.day,
//Title = l.Title,
start = l.From,
end = l.To,
color = "#88CD23"
};
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and now I would like to handle next and back buttons and change start date, end +7 day. I wrote something like this, but doesn't work
C#
public JsonResult GetEventsAdd(int move)
{
//all the same method as in GetEvents, but added days
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddDays(move),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30).AddDays(move)
});
licznik++;
}
}
//all the same method as in GetEvents
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and script was changed
events: function (start, end, timezone, callback) {
var data = { "move": 7 }
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
//data: JSON.stringify(calendar),
//datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
$(".fc-next-button").one("click", function () {
$.ajax({
url: '/Dentist/GetEventsAdd/',
type: 'POST',
data: JSON.stringify(data),
datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//$('#calendar').fullCalendar('refetchEvents');
}
});
});
how can I get such a solution?
The AJAX call that fullcalendar makes passes the start and end date range for the current view. It will then call that again, only if it doesn't have the date stored.
so in your /Dentist/GetEvents/
grab the "GET" variables: "START" and "END".
return the events that are in that range.
then simply use the native 'next', 'prev' buttons from fullcalendar and let it do its thing.
I am using a web service that gets data from my active directory and returns an array of objects to my javascript. The problem is the I am the response encapsulated in Object with _type included when I just want to return the value of the object like this
([{ value: "one", label: "Foo" }, { value: "two", label: "Bar" }]).
But I am receiving this
[Object { __type="Service+NameDTO", value: "one", label: "Foo"}, Object { __type="Service+NameDTO", value: "two", label: "Bar"}]
Here is my c#
public NameDTO[] GetCompletionList(string prefix)
{
var nameList = new List<NameDTO>();
DirectorySearcher search = new DirectorySearcher();
string strPath = search.SearchRoot.Path;
DirectoryEntry entry = new DirectoryEntry(strPath);
search.PageSize = 1000;
search.Filter = "(&(objectClass=user)(objectCategory=person)(displayName=*" + prefix + "*))";
foreach (SearchResult sResultSet in search.FindAll())
{
if (sResultSet.Properties["mail"].Count > 0)
{
var dto = new NameDTO()
{
label = (string)sResultSet.Properties["displayName"][0],
value = (string)sResultSet.Properties["mail"][0],
};
nameList.Add(dto);
}
}
NameDTO[] myArray = nameList.ToArray();
return myArray;
}
public class NameDTO
{
public string label { get; set; }
public string value { get; set; }
}
and my javascript
<script type="text/javascript">
$(document).ready(function () {
$('#tokenfield').tokenfield({
autocomplete: {
source: function (request, response) {
$.ajax({
url: '<%#ResolveUrl("~/Service1.asmx/GetCompletionList") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return data
}))
},
success: function(response) {
$.each(response, function(key, val) {
alert(val.id);
});
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
search: function () {
var term = this.value;
if (term.length < 3) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
},
});
});
</script>
You probably need some typical JSON builder.
Server-side, you can make dictionaries, arrays, etc and throw everything into a
JsonMapper.ToJson(jsonDict)
call.
This function in my project indirectly calls JsonSerializer(), the Newtonsoft JSON handler. Very useful for both serializing and deserializing the JSON.
I may be misinterpreting your question, though; a bit vague.
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx is pretty darn relevant here, and very useful.
It came up that you might need this:
var jsonString = #Model; //or however you get your string.
var json = JSON.parse(jsonString);
I am having some issues with a Webmethod (c#) populating a JQuery DataTable table with JSON data.
Ajax call:
function loadTable(message) {
$.ajax({
type: "POST",
url: "TestBed.aspx/ValueDateSummary",
cache: false,
data: JSON.stringify({ senderBIC: senderBIC }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var data = msg.d;
alert(data["counter"]);
alert(data);
alert(typeof msg);
var otable = $("#test").dataTable({
// "sAjaxDataProp": msg.d,
"aoColumns": [
{ "mDataProp": "counter" },
{ "mDataProp": "SessionID" },
{ "mDataProp": "MsgType" }
]
});
}
});
};
No errors, but the datatable is empty.
Here are the results of the alerts
alert(data["counter"]) = UNDEFINED
alert(data) = [{"counter":3,"SessionID":"1","MsgType":"103","ValueDate":"2007-08-01","Sender":"1"}, {"counter":7,"SessionID":"2","MsgType":"103","ValueDate":"2009-05-26","Sender":"2"}]
alert(typeof msg) = OBJECT
any ideas why my table is empty?
* EDIT *
THIS IS THE FINAL SUCCESS METHOD WHICH WORKED
success: function (msg) {
var data = JSON.parse(msg.d);
$("#test").dataTable({
"aaData": data,
"aoColumns": [{
"mDataProp": "counter"
}, {
"mDataProp": "SessionID"
}, {
"mDataProp": "MsgType"
}]
});
}
You are never settings the data of the oTable...
You have to give it an Array of Arrays (var object = [][]):
You can either do it as ajax and put your $ajax code into the fnServerData function
Or do the following: (taken from example from DataTables)
function loadTable(message) {
$.ajax({
type: "POST",
url: "TestBed.aspx/ValueDateSummary",
cache: false,
data: JSON.stringify({
senderBIC: senderBIC
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var data = [];
$.map(msg.d, function (item) {
{
var row = [];
row.push(
item.counter,
item.SessionID,
item.MsgType
//Commented out because you didn't include them in your aoColumns declaration, if you want them in the table to access later just make them non-visible.
//item.ValueDate,
//item.Sender
);
data.push(row);
}
});
var otable = $("#test").dataTable({
"aaData": data,
"aoColumns": [
{"mDataProp": "counter"},
{"mDataProp": "SessionID"},
{"mDataProp": "MsgType"}
]
});
}
});
}
As of jQuery DataTables 1.7.2 you can use array of objects as a data source but only with the ajax source (sAjaxSource) and it is slightly slower because it just manually copies it to an array or arrays.
Try changing your success function to the following:
var data = msg.d;
alert(data["counter"]);
alert(data);
alert(typeof msg);
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push([
data[i].counter,
data[i].SessionID,
data[i].MsgType,
data[i].ValueDate,
data[i].Sender
]);
}
var otable = $("#test").dataTable({
"aaData": rows
});