Set method from webservice to javascript - c#

I have this function in javascript, which sets all markers and popup info for each marker.
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i < arraylng.length - 1; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(arraylng[i], arraylat[i])
});
var infowindow = new google.maps.InfoWindow({
content: " "
});
makeInfoWindowEvent(map, infowindow, marker, i);
markers.push(marker);
}
function makeInfoWindowEvent(map, infowindow, marker, i) {
google.maps.event.addListener(marker, 'click', function() {
alert(arraylat[i]); // working nice
alert(arraylng[i]); // working nice
infowindow.setContent(arraylng[i] + ", " + arraylat[i]);
infowindow.open(map, marker);
});
}
}
My question is: How can I add my method from webservice, which return an address from database? Here is code.
[WebMethod]
public string GetAddressMarker(string lat, string lng) {
string address = "";
var plac = GoogleapiBO.getClinicByLatLng(lat, lng);
address = plac.address + ", " + plac.city;
address = "'" + address + "'";
return address;
}
All I need, is to get an address from this method (method needs string lat=arraylat[i] & string lng=arraylng[i]) and set it into infowindow.setContent(*here*);
How can I do this?

Solution #1
Webservice:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAddressMarker(string lat, string lng) {
string address = "";
var plac = GoogleapiBO.getClinicByLatLng(lat, lng);
address = plac.address + ", " + plac.city;
address = "'" + address + "'";
return address;
}
Javascript
function makeRequest(url, message) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = getResponse;
httpRequest.open("POST", url, true);
httpRequest.setRequestHeader("Content-Type", "application/json");
httpRequest.send(message);
}
function getResponse() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
//convert JSON string into object
progressInfo(JSON.parse(httpRequest.responseText))
}
}
function progressInfo(info) {
//doing something with object info - in your case it should be the string
}
to call the method:
makeRequest("http://..../webservice/Service.asmx/GetAdressMarker");
Solution #2
setting a javascript variable in the c# code:
<script type="text/javascript">
var address= '<%= _address%>';
</script>
code-behind:
public partial class Entscheidungen : System.Web.UI.Page
{
private string _address;
protected void Page_Load(object sender, EventArgs e)
{
bt.Command += new CommandEventHandler(bt_Command);
}
void bt_Command(object sender, CommandEventArgs e)
{
_address = Service.GetAddressMarker(string lat, string lng)
}
....
}

try this it may be use full for u
<script type="text/javascript" language="Javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
var webServiceUrl = "../MathService.asmx/GetFullName";
$("#btnAjax").click(function() {
var webServiceUrl = "../MathService.asmx/GetFullName";
var name = $("#txtBoxName").val();
$.ajax({
type: "POST",
url: webServiceUrl,
data: "{'name':'" + name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: SuccessCallBack,
error: FailureCallBack
});
});
function SuccessCallBack(data) {
alert(data.d);
}
function FailureCallBack(data) {
alert(data.staus + " : " + data.statusText);
}</script>
don't forget to add this attribute to the service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAddressMarker(string lat, string lng) {
string address = "";
var plac = GoogleapiBO.getClinicByLatLng(lat, lng);
address = plac.address + ", " + plac.city;
address = "'" + address + "'";
return address;
}

Related

how to post json array list to web service method?

i write two functions in jquery client side and c# asp.net server side , i try post json list object to web method but i see error..
jquery code :
function UpdateCart(tableid) {
var page = "Account/Cart.aspx";
var method = "Update_Cart";
var url = "http://" + host + "/" + page + "/" + method;
$(".popup").show();
var cartlist = new Array();
for (var i = 68; i < 71; i++) {
var cart = new Object();
cart.ID = i;
cart.Quantity = 6;
cartlist.push(cart);
}
var jsonArray = JSON.parse(JSON.stringify(cartlist))
$.ajax({
type: "POST",
url: url,
data: jsonArray,
contentType: "application/json; charset=utf-8",
datatype: "json",
async: "true",
success: function (response) {
// success message or do
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject == 1) {
window.location.href = "http://" + host + "/Account/cart";
} else {
$(".errMsg").text("نام کاربری یا رمز اشتباه است");
$(".errMsg").removeClass("alert");
$(".errMsg").addClass("alert alert-danger");
}
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
c# web method :
[WebMethod]
public static string Update_Cart(string[] Carts)
{
if (Carts != null)
{
foreach (var item in Carts)
{
com_Shop_Carts cart = new com_Shop_Carts()
{
Quantity = item.Quantity,
AddDate = DateTime.Now
};
com.shop.ProductManager.Update_Cart(item.ID, cart).ToString();
}
}
return "1";
}
after run i see error 500 and i can't resolve it please give me solution for resolve it.
Apart from this : var jsonArray = JSON.parse(JSON.stringify(cartlist))
Try this : var json={"Carts":cartlist}; then, var jsonArray=JSON.stringify(json);
and remove datatype:json from the ajax call.
Hope this helps.

Generate a json string in a Ajax WebMethod and send it back to the aspx

I am trying to generate a json string in a Ajax WebMethod and send it back to the aspx success result and printout the results. The json2 string is not correct. Any suggestions?
Default.aspx.cs
[System.Web.Services.WebMethod]
public static string GetJSONdata(string id)
{
string json2 = "";
string val = "1;2;3;4;5";
string[] arr = val.Split(';');
string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
string cmdStr = "SELECT ([datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=#idd;";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#idd", id);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
arr[1] = rdr[1].ToString();
arr[2] = rdr[2].ToString();
arr[3] = rdr[3].ToString();
arr[4] = rdr[4].ToString();
}
}
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
json2 = "{'datajson' : [{'id' : '" + id + "', 'datetime' : '" + arr[1] + "', 'col1' : '" + arr[2] + "', 'col2' : '" + arr[3] + "', 'col3' : '" + arr[4] + "'}]}";
return json2;
}
Default.aspx
<script type="text/javascript" src="~/Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Button1.ClientID %>").click(function () {
var id = $("#<%= TextBox1.ClientID %>").val();
var data = { ID:id };
var json1 = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetJSONdata",
data: json1,
dataType: "json",
success: function (result) {
$("#<%= TextBox2.ClientID %>").val(result.datajson[0].id);
$("#<%= TextBox3.ClientID %>").val(result.datajson[0].datetime);
$("#<%= TextBox4.ClientID %>").val(result.datajson[0].col1);
$("#<%= TextBox5.ClientID %>").val(result.datajson[0].col2);
$("#<%= TextBox6.ClientID %>").val(result.datajson[0].col3);
},
error: function (Msg) {
$("#<%= Label1.ClientID %>").text('failed:' + Msg.status + ' response:' + Msg.responseText);
}
}); return false;
});
});
Error code:
failed:500 response:{"Message":"Invalid web service call, missing value for parameter: \u0027id\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
The post keys must match
Don't stringify the data
Use a library to build JSON don't do it manually (see #joe comment)
ajax:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetJSONdata",
data: {clientId : id },
success: function (result) {...},
error: function (Msg) {...}
});
C#:
[System.Web.Services.WebMethod]
public static string GetJSONdata(string clientId){...}
Building JSON:
Use a library , JSON.NET is a good one. The way it works, you create a model:
public class Datajson
{
public string id { get; set; }
public string datetime { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
Then use it to build your string
List<Datajson> data = new List<Datajson>();
Datajson json = new Datajson();
json.id = clientId;
json.datetime = rdr[1].ToString();
json.col1 = rdr[2].ToString();
json.col2 = rdr[3].ToString();
json.col3 = rdr[4].ToString();
data.add(json);
var jsonString = JsonConvert.SerializeObject(data);
then log it to see.
Just a guess...
But you're expecting "id" in GetJSONdata while you're sending "ID" in ajax request. Might want to keep both of them consistent

Why my data is not updating in mvc4?

When i am going to update data it alert me a error like "Status = Problem : Fail to Update Client Info". I have run this code without db.Update(ci); code, even without any update code it shows me "Successfully Updated.". But when i am used update method it is not executing. where is the problem i can not defined.... Here is my controller code..
public ActionResult Update(ClientInfo client, string id)
{
//Response.Write("Id : " + id + "<br>");
//Response.Write("Country : " + client.Country + "<br>");
try
{
//if (ModelState.IsValid)
//{
ClientInfo ci = db.Single<ClientInfo>("Where CId=" + id);
if (ci != null)
{
ci.CName = client.CName.ToString();
ci.CCName = client.CCName.ToString();
ci.Address = client.Address.ToString();
ci.PhoneNo = Convert.ToInt32(client.PhoneNo.ToString());
ci.Fax = client.Fax.ToString();
ci.Email = client.Email.ToString();
ci.Country = client.Country.ToString();
ci.PostalCode = Convert.ToInt32(client.PostalCode.ToString());
//ci.Update();
db.Update(ci);
return Json(new { msg = "Successfully Updated."});
}
else
return Json(new { msg = "Fail to Update Client Info." });
//}
//return RedirectToAction("Index");
}
catch
{
return Json(new { msg = "Problem : Fail to Update Client Info." });
}
}
And my script for post data to the server
$('#btnUpdate').click(function () {
var CId = $("#CId").val();
var CName = $("#CName").val();
var CCName = $("#CCName").val();
var PhoneNo = $("#PhoneNo").val();
var Fax = $("#Fax").val();
var Email = $("#Email").val();
var Address = $("#Address").val();
var PostalCode = $("#PostalCode").val();
var Country = $("#Country").val();
var client1 = {
"CId": CId,
"CName": CName,
"CCName": CCName,
"PhoneNo": PhoneNo,
"Fax": Fax,
"Email": Email,
"Address": Address,
"PostalCode": PostalCode,
"Country": Country
};
var lk = "/Clients/Update/" + CId;
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert("Status = " + data.msg);
},
error: function (data) {
alert("Error = " + data.msg);
}
});
You are not passing your data correctly. Your link is also incorrectly generated. Since you are passing two objects to your view, it's better to specify both in the ajax data object:
var lk = "/Clients/Update/"; // => removed the CId
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
url: lk,
type: 'POST',
data: { client: client, id = CId } // => added an object containing all the expected parameters
dataType: "json",
success: function (data) {
alert("Status = " + data.msg);
},
error: function (data) {
alert("Error = " + data.msg);
}
});

No response from generic handler

I have problem in my AjaxHandler.ashx becouse the context.Request["Action"] is null when I send it using JQuery call can someone help me
Note: I'm using html controller not asp,net server controller
<script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
/*var skill = $("#ddlSkills option:selected").val();
var types = $("#ddlTypes option:selected").val();
var topics = $("#ddlTopics option:selected").val();
var sortBy = $("#ddlSortBy option:selected").val();
*/
$.ajax({
url: "../ideapark/DesktopModules/ResourcesFilter/AjaxHandler.ashx",
contentType: "application/json; charset=uft-8",
type: "POST",
data: $('form').serialize(),
success: function(data) {
for(var i = 0; i < data.length; i++)
{
//t ajax handler recollection of resources.
//U NEED TDESERIALIZE
var resID = data.response[i].ID;
var summary = data.response[i].Summary;
var pageID = data.response[i].PageID;
var name = data.response[i].Name;
var createdOn = data.response[i].CreatedOn
var Total = data.response[i].Total;
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
alert(XMLHttpRequest);
alert(textStatus);
console.log(errorThrown);
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
});
</script>
/// <summary>
/// Summary description for AjaxHandler
/// </summary>
public class AjaxHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
//context.Response.Write("Hello World");
string response = "";
string var = context.Request["Action"].ToString();
switch (context.Request["Action"])
{
case "ResponseFilterSearch":
response += "{";
Dictionary<string, Object> jsonObject = new Dictionary<string, object>();
string skill = context.Request["Skill"].ToString();
string type = context.Request["Type"].ToString();
string focus = context.Request["focus"].ToString();
string keyword = context.Request["Keyword"];
string sortby = context.Request["SortBy"];
string pageNumber = context.Request["pagenumber"];
SqlDataProvider sqlConn = new SqlDataProvider();
DataSet dsResults = SqlHelper.ExecuteDataset(sqlConn.ConnectionString, "spResourceSearch", skill, type, focus, keyword, sortby, pageNumber);
foreach (System.Data.DataRow row in dsResults.Tables[0].Rows)
{
response += "\"ID\":" + "\"" + row["Id"].ToString() + "\"";
response += "\"Summary\":" + "\"" + row["summary"].ToString() + "\"";
response += "\"PageID\":" + "\"" + row["pageId"].ToString() + "\"";
response += "\"Name\":" + "\"" + row["name"].ToString() + "\"";
response += "\"CreatedOn\":" + "\"" + row["createdOn"].ToString() + "\"";
response += "\"Total\":" + "\"" + row["total"].ToString() + "\"";
}
response += "}";
break;
}
//this returns a json string
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
You seem to be mixing up contentType and dataType.
contentType represents the the content type of the request body(that is the data you're sending to the server), which you've set to json which is not what $('form').serialize() will produce. $('form').serialize() produces data in application/x-www-form-urlencoded which is the default in $.ajax.
Now dataType is the content type of the response body(which is the data you receive from the server) which from your code should be json.
$.ajax({
url: "../ideapark/DesktopModules/ResourcesFilter/AjaxHandler.ashx",
dataType: "json",
type: "POST",
data: $('form').serialize(),
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
....
}
});

ReferenceError: getMessage not defined

I am building a messaging area similar to facebook and I am using ajax with jquery and a asmx web service to serve the html to the client. My li click event works when the content is first loaded on page load using c#, but when ajax runs and refreshes the content from the web service the li event doesn't work anymore.
This an example of the html that is returned from the web service
<ol class="messagesrow" id="messages">
<li id="2345">
<div>Test Element</div>
</li>
</ol>
Web service markup
[WebMethod]
public string GetMessagesByObject(string id, string objectid, string userid, string timezone)
{
string output = string.Empty;
try
{
StringBuilder str = new StringBuilder();
DataSet results = results from store procedure
str.Append("<ol class=\"messagesrow\" id=\"messages\">");
for (int i = 0; i < results.Tables[0].Rows.Count; i++)
{
DataRow row = results.Tables[0].Rows[i];
DateTime date = Convert.ToDateTime(row["CreateDate"].ToString()).AddHours(Convert.ToDouble(timezone));
if (!TDG.Common.CheckStringForEmpty(row["ParentMessageID"].ToString()))
{
str.Append("<li id=\"" + row["ParentMessageID"].ToString() + "\">");
}
else
{
str.Append("<li id=\"" + row["MessageID"].ToString() + "\">");
}
str.Append("<div style=\"width:100%; cursor:pointer;\">");
str.Append("<div style=\"float:left; width:25%;\">");
if (!TDG.Common.CheckStringForEmpty(row["ImageID"].ToString()))
{
str.Append("<img src=\"/Resources/getThumbnailImage.ashx?w=48&h=48&id=" + row["ImageID"].ToString() + "\" alt=\"View Profile\" />");
}
else
{
str.Append("<img src=\"/images/noProfileImage.gif\" alt=\"View Profile\" />");
}
str.Append("</div>");
str.Append("<div style=\"float:left; width:75%; padding-top:4px;\">");
str.Append("<strong>" + row["WholeName"].ToString() + "</strong>");
str.Append("<br />");
if (row["BodyMessage"].ToString().Length < 35)
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString() + "</span>");
}
else
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString().Substring(0, 35) + "</span>");
}
str.Append("<br /><span class=\"smallGreyText\">" + String.Format("{0:g}", date) + "</span>");
str.Append("</div>");
str.Append("</div>");
str.Append("</li>");
}
str.Append("</ol>");
output = str.ToString();
}
catch (Exception ex)
{
throw ex;
}
return output;
}
Jquery markup
$(document).ready(function () {
$("ol#messages li").click(function () {
var id = $(this).attr("id");
getMessage(id);
});
});
function getMessage(id) {
var timezone = $('#<%= hdfTimezone.ClientID %>').val()
var userid = $('#<%= hdfUserID.ClientID %>').val()
$.ajax({
type: "POST",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Resources/MessageWebService.asmx/GetMessage",
data: "{'id':'" + id + "','timezone':'" + timezone + "','userid':'" + userid + "' }",
success: function (data) {
$('#<%= hdfMessageID.ClientID %>').val(id);
$('#<%= ltlMessages.ClientID %>').html(data.d);
},
error: function (data) {
showError(data.responseText);
}
});
}
Since your list items are dynamic, you should delegate the event from the ol.
$(document).ready(function () {
$("#messages").delegate("li","click",function () {
getMessage(this.id);
});
});
The error you are getting ReferenceError: getMessage not defined shouldn't happen with the given code.

Categories