Ajax and ASP.NET full string not being sent properly - c#

I have an ajax call like so:
$.ajax({
type: "GET",
url: "/api/connection/NotifiyNextDepartment?questionId="
+ highestValue + "&department=" + jobTitle + "&customerId=" + customerID + "&jobNumber="
+ $("#communtiyDropdown").val() + $("#lotDropdown").val(),
dataType: "json",
cache: false,
success: function (data) {}
});
alert('Success, you\'re data has been saved!');
holder = [];
},
failure: function (errMsg) {
alert('Failed, somthing went wrong, please try again!');
}
jobTitle is equal to "Human Resources & Customer Experience Manager"
when I send it to .NET I only get this back:
public bool NotifiyNextDepartment(int questionid, string department, int customerId, string jobNumber)
{
}
Here department is equal to "Human Resources "
Why is .NET removing everything after the & and how do I fix this?

I think you should call encodeURIComponent on your parameters.
url: "/api/connection/NotifiyNextDepartment?questionId="
+ encodeURIComponent(highestValue) + "&department=" + encodeURIComponent(jobTitle) + "&customerId=" + encodeURIComponent(customerID) + "&jobNumber="
+ encodeURIComponent($("#communtiyDropdown").val() + $("#lotDropdown").val()),

Related

Service method name is not valid. from Hosted server

I got this error
System.InvalidOperationException: ManageUser Web Service method name
is not valid. at
System.Web.Services.Protocols.HttpServerProtocol.Initialize() at
System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type,
HttpContext context, HttpRequest request, HttpResponse response,
Boolean& abortProcessing)
when I trying to call a webservice method from button click event using ajaxcall
$.ajax() {
type: "POST",
url: "RechargeService.asmx/ManageUser",
//data: "{objUser: " + JSON.stringify(objUsers) + "}",
data: "{Name:'" + Name + "',Address:'" + Address + "',City:'" + City + "',State:'" + State + "',Pincode:'" + Pincode + "',MobileNo:'" + MobileNo + "',Email:'" + Email + "',Password:'" + Password + "',Parameter:'" + Parameter + "',UserRole:'" + UserRole + "',UserStatus:'" + UserStatus + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (data) {
data = JSON.parse(data.d);
if (data.Sucess) {
$("#lblMsg").html('Registration done successfully');
$("#txtEmail").val('');
$("#txtPassword").val('');
$("#txtMobileNo").val('');
$("#txtConfirmPassword").val('');
$('#myModal1').hide();
alert("Your registration completed successfully");
} else {
alert("Already registered with this email id");
$("#txtEmail").val("");
}
},
error: function (xhr, status, error) {
alert(xhr.responseText + " \n " + status + " \n " + error);
alert("There was an error while processing. Please try again after some time.");
}
}
Method
[WebMethod]
Public string ManageUser()
{
}
This code works fine in local after hosting only i get the above error pls help me with this.. Thanks in advance
This can be caused by having null valued parameters in your WebMethod.
For example this:
public string GetDocument(int templateId, int? loginId = null)
...should be changed to this:
public string GetDocument(int templateId, int loginId)
There is a missing brackets () in the ajax function that should be Like this
$.ajax({
//Your Code...
});
Try this...
Possible REASON 1:
did u add this in above the service class
[System.Web.Script.Services.ScriptService]
Possible Reason 2:
Data should have sigle quotes for patameter names as well
data:{'Name':'" + Name + "','Address':'" + Address + "'}

passing string array from ajax to c# web method

Hi I have this code below
How could I pass preferably 1 array which will contain an ID number and a value from a textbox which is dynamically generated and then passed to the backend to C#
var listoftextboxesWithValues = new Array();
var listoftextboxesWithID = new Array();
var i = 0;
$.each(listOftxtPriceTypeID, function (index, value) {
listoftextboxesWithID[i] = value.ID.toString();
listoftextboxesWithValues[i] = $("#txtPriceTypeID" + value.ID).val().toString();
i++;
});
//---Till here the data in the above arrays is as expected, the problem starts below in the data :
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data: "{subCategoryID : '" + parseInt(subcategoryID) + "',name: '" + name + "',description: '" + description + "',quantity: '" + parseInt(quantity) + "',supplier: '" + supplier + "',vatRate: '" + parseFloat(VatRate) + "',colorID: '" + parseInt(colorID) + "',brandID: '" + parseInt(brandID) + "',imagePath: '" + fileNameGUID + "',listOfTextBoxes: '" + JSON.stringify(listoftextboxesWithValues) + "',listOfTextBoxesValues: '" + JSON.stringify(listoftextboxesWithID) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
[WebMethod]
public static void StoreNewProduct(int subCategoryID, string name, string description, int quantity,
string supplier, float vatRate, int colorID, int brandID, string imagePath, string[] listOfTextBoxesID, string[] listOfTextBoxesValues )
{
Product p = new Product();
ProductPriceType ppt = new ProductPriceType();
p.CategoryID = subCategoryID;
p.Name = name;
p.Description = description;
p.Quantity = quantity;
p.Supplier = supplier;
// p.VATRate = vatRate;
p.ColorID = colorID;
p.BrandID = brandID;
p.Image = imagePath;
//...
}
Any help would be much appreciated
if I will do it, my approach is to seperate those two,
create string array for texts
create string array for values
i believe that the number of values will be the same with texts since it is generated dynamically.
then pass those two string arrays in c# backend.
you can use json2.js is cool ,I used this
var valueObj = { field1: $("input[name=field1]").val(),
field2: $("input[name=field2]").val()}
and then I can parse with this:
JSON.stringify(valueObj)
in the ajax call you can use like this
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data:valueObj ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
//In JS file
var arr = [];
arr.push( $("#textZipcode").val());
arr.push( $("#textPhone").val());
arr.push($("#textAddress").val());
arr.push( $("#textMobile").val());
//You can add any number. It will store to array properly.
$.ajax({
type: "POST",
url: "HomePage.aspx/SaveData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:JSON.stringify({arr:arr}),
success: function (response) {
}});
//In C#
[WebMethod]
public static void SaveData(string[] arr)
{
}

How to use ScriptManager.RegisterStartupScript in a WebMethod in asp.net?

I have a condition where i need to call a jquery function using a webmethod as below:
[WebMethod]
public static void BindData(String Site)
{
String HTML = "";
Int32 i = 1;
DataTable dt = new DataTable();
dt = obj.GetAll(objprop);
if (dt.Rows[0]["UserId"].ToString() != "0")
{
foreach (DataRow item in dt.Rows)
{
string Email = Bal.Common.Decryptdata(item["Email"].ToString());
string SentInvitation = item["SentInvitation"].ToString();
SentInvitation = SentInvitation.ToString() == "1" ? "Already Invited" : "";
if (i % 2 == 0)
HTML += "<div class=~other_wish_row2~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
else
HTML += "<div class=~other_wish_row3~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
i = i + 1;
}
ScriptManager.RegisterStartupScript((Page)(HttpContext.Current.Handler), typeof(Page), "hdrEmpty1", "Test('" + HTML + "');", true); return;
}
else
{
}
}
Jquery Code is:
function Test(data) {
alert('hi');
}
function Binddata(SocialSite) {
$.ajax({
type: "POST",
url: "InviteFriends.aspx/BindData",
data: "{SocialSite:'" + SocialSite + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}
});
}
I am not able to fire Test(), please help to resolve this.
You can't do this from a web service (either an .asmx file or a WebMethod) as it does not run in the context of a normal page. I see you're using AJAX, you'll have to do the handling in the success callback method of your jQuery.ajax() call, like so:
function Test(data) {
alert('hi');
}
function Binddata(SocialSite) {
$.ajax({
type: "POST",
url: "InviteFriends.aspx/BindData",
data: "{SocialSite:'" + SocialSite + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Test(data);
}
});
}

how to fetch return values between jquery functions and post ajax jquery request to webservice

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

call method in code behind from JQuery

I am trying to execute a method in ASP.NET from Jquery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyMessages.aspx?id=66&epslanguage=sv/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
}
})
code behind:
[WebMethod]
protected void test()
{
test.Text = "works";
}
I get errormessage redayState: 4 and status 200 when I do this. I don't understand the problem. I am vey new at this. :)
data: "{}", should be just data: {}, or just remove it if not in use,,..
as a first your method should be static and public
so instead of this
[WebMethod]
protected void test()
{
test.Text = "works";
}
it should be
[WebMethod]
public static void test()
{
test.Text = "works";
}
this is the first fix
the second you can't access the test.text
so if u wanna make sure it works you can
write it in this way
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
so your final code should be like this
[WebMethod]
public static void test()
{
//test.Text = "works";
}
and Ajax method
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
I did change the URL for u
and if you wanna pass parameters you pass them on Data Section of Ajax method
some thing like this
'{"fname":"' + fname + '","lname":"' + lname + '","email":"' + email + '","address":"' +
I wish it helps you
address + '"}'

Categories

Resources