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)
{
....
}
});
Related
I have a AJAX call for controller as below,
function print(response, endpoint) {
$(".tt").append("<tr><td>" + JSON.stringify(response[0], null) + "</td><td>" + JSON.stringify(response[1], null) + "</td><td>" + JSON.stringify(response[2], null) + "</td><td>" + JSON.stringify(response[3], null) + "</td><td>" + JSON.stringify(endpoint, null) + "</td></tr>");
}
$(".submit").click(function () {
var env = $("#env").find(":selected").text();
var region = $("#region").find(":selected").text();
var country = $("#country").find(":selected").text()
var folderPath = $.trim($('#folderPath').val());
var ajaxRequest = $.ajax({
contentType: "application/json ;charset=utf-8",
type: "GET",
async: false,
url: "/Home/GetmyModel" + "?selcetion=" + env + "®ion=" + region + "&country=" + country + "&folderpath=" + folderPath,
success: function (response) {
if (response != null) {
//print(response, endpoints[i]);
}
},
error: function (exception) {
},
complete: function (data) {
}
});
My controller goes like this
public void GetmyModel(string selcetion, string region, string country, string folderpath)
{
foreach (var item in System.IO.File.ReadLines(folderpath))
{
//do some work with return value as list<string>
//show list<string> in table in view using either print method of JS or by another way
}
}
Everything works fine if i send complete response back by making return type as JsonResult. However i am not understanding how can i print each item.
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.
I have a WebMethod which gets data that I want to fill DropDown with in a DataSet.
Currently I am filling the dropdown using a hardcoded object. But I want to replace this hard coded object with data returned by webmethod.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return ds.GetXml();
}
CLIENT SIDE(UPDATE 1):
<script type = "text/javascript">
function GetDropDownData() {
var myDropDownList = $('.myDropDownLisTId');
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(jQuery.parseJSON(data.d), function () {
myDropDownList.append($("<option></option>").val(this['FieldDescription']).html(this['FieldCode']));
});
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
console.log(response.d);
alert(response.d);
}
</script>
function GetDropDownData() {
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data.d)
{
$.each(data.d, function (){
$(".myDropDownLisTId").append($("<option />").val(this.KeyName).text(this.ValueName));
});
},
failure: function () {
alert("Failed!");
}
});
}
var theDropDown = document.getElementById("myDropDownLisTId");
theDropDown.length = 0;
$.each(items, function (key, value) {
$("#myDropDownLisTId").append($("<option></option>").val(value.PKId).html(value.SubDesc));
here "SubDesc",PKId describes the value getting out of Database., u need to separate your value from dataset.
From the WebMethod, don't send DataSet directly, send XML...
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
DataSet ds = new DataSet();
ds.Tables.Add("Table0");
ds.Tables[0].Columns.Add("OptionValue");
ds.Tables[0].Columns.Add("OptionText");
ds.Tables[0].Rows.Add("0", "test 0");
ds.Tables[0].Rows.Add("1", "test 1");
ds.Tables[0].Rows.Add("2", "test 2");
ds.Tables[0].Rows.Add("3", "test 3");
ds.Tables[0].Rows.Add("4", "test 4");
return ds.GetXml();
}
Before Ajax call...
var myDropDownList = $('.myDropDownLisTId');
Try like below...(inside Ajax call)
success: function (response) {
debugger;
$(response.d).find('Table0').each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
myDropDownList.append(option);
});
},
Note:
OptionValue and OptionText are the Columns of DataSet Table.
$(response.d).find('Table0').each(function (){}) - Here Table0
is the name of Table inside DataSet.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return DataSetToJSON(ds);
}
public static string DataSetToJSON(DataSet ds)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
var lstJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
return lstJson;
}
Ajax Call
function GetAssociation() {
var myDropDownList = $("#myDropDownLisTId");
var post_data = JSON.stringify({ "name": "xyz"});
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: post_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
json_data = JSON.parse(response.d);
myDropDownList.empty();
for(i=0; i<json_data.Table.length; i++)
{
myDropDownList.append($("<option></option>").val(json_data.Table[i][0]).html(json_data.Table[i][1]));
}
},
failure: function (response) {
alert(response.d);
}
});
}
// We can bind dropdown list using this Jquery function in JS script
function listDropdownBind() {
var requestId = 123;
$.ajax({
type: "POST",
url: "/api/ControllerName/ActionName?param=" + param, // call API with parameter
headers: { 'rId': requestId },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '';
var optionhtml1 = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$("#ddlName").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data.d[i].Value + '">' + data.d[i].Text + '</option>';
$("#ddlName").append(optionhtml);
});
}
});
};
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);
}
});
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;
}