good evening,
j tries to retrieve the data from the user but the problem iƧ that i can not handle the coords because of "," longitude and latitude, i do not know how to treat these give, i tried with parsefloat but without result, thank you
code controller action :
public ActionResult GetNeaarByLocations(string CurrentLat, string CurrentLng)
{
using (GeolocationTestEntities context = new GeolocationTestEntities ())
{
var CurrentLocation = DbGeography.FromText("POINT(" + CurrentLat + " " + CurrentLng + ")");
//var CurrentLocation = DbGeography.FromText("POINT(36,806494799999996 10,181531600000001)");
var places = (from u in context.schoolinfo orderby u.Location.Distance(CurrentLocation)
select u).Take(4).Select(x=>new schoollinfo(){ Name = x.name ,Lat = x.Location.Latitude, Lng = x.Location.Longitude,Distance = x.Location.Distance(CurrentLocation)});
var nearschools = places.ToList();
return Json(nearschools , JsonRequestBehavior.AllowGet);
}
}
and this is code Ajax :
jQuery.ajax({
cache: false,
type: "POST",
url: "#Url.Action("GetNeaarByLocations")",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ CurrentLng:currentLatLng.longitude, CurrentLat: currentLatLng.latitude }),
success: function (data) {
if (data != undefined) {
$.each(data, function (i, item) {
addMarker(item["lat"], item["lng"], "Click to get directions");
})
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
thanks all.
we need to convert lng & lant to double
var currentLatLng = position.coords;
var Lat = currentLatLng.latitude;
var Lng = currentLatLng.longitude;
var LatDouble = parseFloat(Lat);
var LngDouble = parseFloat(Lng);
for Ajax is to delete att stringify
data: JSON({ CurrentLng:LngDouble , CurrentLat: LatDouble }),
Related
Here is my controller. I am trying to pass the value through an if statement but it's not equalling (==) the string of "2019".
[HttpPost]
public ActionResult Extract(string[] response)
{
string statementQuery = "";
if (response!=null)
{
for (var i = 0; i < response.Length; i++)
{
if (response[i] == "2019")
{
statementQuery = "select statementPath from ClientStatements_Inventory where statementYear = '" + response[i] + "';";
}
}
}
Here is my ajax call. Is it something to do with the way it is sending to my controller? or my if statement?
$('#main-content-submit').click(function () {
var labelArray = [];
labelArray = $("input:checkbox:checked").map(function () {
return $(this).closest('label').text();
}).get();
console.log(labelArray);
event.preventDefault();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ response:labelArray }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert("Month and ear passed to controller");
},
error: function (err, result) {
alert("Error in Extract" + err.responseText);
},
});
return false;
});
I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}
I have an observable array Object that which is generated like this:
self.SelectedVariable = ko.observableArray();
self.VarUpdate = function (data) {
$.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
for (var i = 0; i < Result.length; i++) {
element = Result[i];
self.SelectedVariable({ VariableID: ko.observable(element.VariableID), VariableDateLastUpdated: ko.observable(element.VariableDateLastUpdated), VariableName: ko.observable(element.VariableName), VariableDescription: ko.observable(element.VariableDescription), VariableValue: ko.observable(element.VariableValue), VariableType: ko.observable(element.VariableType) });
};
});
When I try to pass the SelectedVariable object to my WebAPI method using this AJAX call
$.ajax({
url: "/api/Variable?Del=0",
data: { vardata: ko.toJS(self.SelectedVariable) },
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
, all the related object shows null on all the fields.
I have tried almost every combination to get the SelectedVariable Object to parse correctly to my WebAPI method:
data: { vardata: ko.toJS(self.SelectedVariable) },
data: { vardata: ko.toJSON(self.SelectedVariable) },
data: { vardata: JSON.Stringify(self.SelectedVariable) },
data: { vardata: self.SelectedVariable },
and have tried to manually decrypt JSON object on WebAPI side using:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata);
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
And It is still null value.
Any Advice would be greatly appreciated!
UPDATE
Changed my WebAPI method to reflect as follows:
public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
var Item = (from c in TMIRE.Variables
where c.VariableID == vardata.Select(x => x.VariableID).First()
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
vardata.Select(a => Item.VariableName = a.VariableName);
vardata.Select(b => Item.VariableDescription = b.VariableDescription);
vardata.Select(c => Item.VariableValue = c.VariableValue);
vardata.Select(d => Item.VariableType = d.VariableType);
}
and now the vardata object gets the value but all objects within are null
My Ajax method looks like this:
alert(ko.toJSON(self.SelectedVariable));
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable()),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
The alert gives me this response
The Variables Class
public class Variables
{
public int VariableID { get; set; }
public DateTime VarialbeDateLastUpdated { get; set; }
public string VariableName { get; set; }
public string VariableDescription { get; set; }
public string VariableValue { get; set; }
public string VariableType { get; set; }
}
Working Code
By using this Ajax call
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
and then using Newtonsoft to deserialize the object on WebAPI using this method:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
}
else
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableActive = false;
}
TMIRE.SaveChanges();
}
I Got it to work
Try this...
public void Put([FromUri] int Del, IEnumerable<Variables> vardate){}
Since you're building a collection on the client self.SelectedVariable = ko.observableArray();, you will need the API to receive an IEnumerable.
In the Ajax call, I think it would be best to use:
data: { vardata: ko.toJSON(self.SelectedVariable) }
as this will give you a JSON representation of the collection.
Also, on the KO side, shouldn't you be pushing elements into the collection? self.SelectedVariable.push({...}); or you will end up with only the final result.
Change assignment to this:
self.SelectedVariable = ko.observableArray();
self.VarUpdate = function (data) {
$.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
var selection = self.SelectedVariable;
for (var i = 0; i < Result.length; i++) {
var element = Result[i];
selection.push(element);
};
});
Then, Change the ajax method to convert to json:
$.ajax({
url: "/api/Variable?Del=0",
content-type: "application/x-www-form-urlencoded",
data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable)),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
Also try removing [FromBody].
public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
...
}
It looks like making the serialized objects in vardata as ko.observable objects is confusing mvc serialization for the parameters.
different data assignments to attempt:
data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable))
data: "=" + JSON.stringify(self.SelectedVariable())
data: "=" + self.SelectedVariable()
data: "=" + $.parseJSON(ko.toJSON(self.SelectedVariable))
What you're passing self.SelectedVariable isn't an array. Should you not be calling it just an observable? Otherwise, you need to be adding your results with self.SelectedVariable.push(resultObject).
By using this Ajax call
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
and then using Newtonsoft to deserialize the object on WebAPI using this method:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
}
else
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableActive = false;
}
TMIRE.SaveChanges();
}
I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},
I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}