Sending a simple bool value from javascript to a c# web service - c#

[I realise this might seem like a stupid question but I am lost.]
Using umbraco 4.9 I have a multi-lingual site where I have made an event handler to replicate content nodes to all languages as they are created in the back office to all languages. I am now trying to attach this to a custom context menu item(umbraco.interfaces.IAction) to give the creator a choice.
In the context menu item it is only possible to call a javascript function as a string. I shouldn't touch the umbraco code itself so how can I pass a value to a web service? Where do I include the reference?
This is what I have at the moment:
public string JsSource
{
get
{
return "function AddItem(){" +
"var multiLang = confirm('Create for all languages?');" +
//"$.ajax({" +
//"type: 'Post'," +
//"url: 'TryAgain.aspx/' + SendMultiVal" +
//"data: multiLang})" +
//"PageMethods.SendMulti(multiLang);}" +
string.Format("{0}.actionNew()", ClientTools.Scripts.GetAppActions)+"};";
}
}
Thanks in advance.

So the first thing that you need to do is to store the boolean value in a variable called boolvalue and then call the callservice function once you have the value.For eg:
CallService("POST", "YourServiceUrl",boolvalue,
function (data) {
alert("Service Call Success");
},
function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
});
This will make a service call and get data from service if it returns some data.
CallService = function (method, serviceUrl, value, successHandler, errorHandler) {
$.ajax({
type: method,
url: serviceUrl,
contentType: "application/text; charset=utf-8",
dataType: "json",
data:JSON.stringify(value),
success: successHandler,
error: errorHandler
});
};
Modify the dataType and dataType fields depending upon the type of data that you send and receive from the service.
Look into this if you need more information:
http://api.jquery.com/jQuery.ajax/
Let me know if this works out for you.

Related

Updates in the server backend are not being published to the web client

I am creating a backend service that writes new articles into a database and, upon completion, publishes changes to listening client in the frontend layer. My problem is that these BE updates are not triggering my subscribers in the frontend layer.
Directly testing the TaskHub (signalR backend asp.net hub) layer seems to be working, but the UI is not being updated. Relevant code for the various layers follows (I might be missing a thing or two - ask if something is amiss).
The order of things :
starting off with calling this on the client side:
var taskHub = $.connection.taskHub;
$.connection.hub.start();
Then i have this Knockout function to do the update :
self.AddQuickNews = function() {
taskHub.server.AddAndUpdateQuickNews(self.newContent()); /just a string
}
On ASP.NET backend i have the following method to handle this :
public void AddAndUpdateQuickNews(string newContent)
{
ArticleServices.AddQuickNews(newContent); //add a new record
var quicknews = ArticleServices.GetQuickNews(); // get all records
Clients.All.updateQuickNews(quicknews); // pass back to clients
}
Handling the result on the Client :
taskHub.client.UpdateQuickNews = function (quicknews) {
quicknewsmodel.quicknews(quicknews);
console.log("SignalR -> " + quicknews);
//console.log("Fra UpdateMatches: " + matches);
}
XHR call to test the backend
self.AddQuickNews = function () {
var url = 'api/MainPage/AddQuickNews';
var params = "?content=" + self.newContent();
$.ajax({
url: url + params,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
taskHub.server.updateQuickNews(data);
},
error: function () {
//alert("error");
}
});
}
The way I see it, its because when You declare the listener in your Client Side, you are using Upper Case in the first letter. This behavior is not allowed in SignalR. You must change your listener becomes :
taskHub.client.updateQuickNews = function (quicknews) {
quicknewsmodel.quicknews(quicknews);
console.log("SignalR -> " + quicknews);
//console.log("Fra UpdateMatches: " + matches);
}
taskHub.server.addAndUpdateQuickNews(self.newContent()); /just a string
Hope this would help you

How to get data from Soap service by jquery?

I want to get data from Webservice( Soap), but it not successfull. My service herehttp://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl
I use jquery to request to service, code below
var soap = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<Test xmlns=''>" +
"</Test>" +
"</soap:Body>" +
"</soap:Envelope>";
$.ajax({
url: 'http://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl',
method: 'post',
data: soap,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "urn:evsServiceUtility/Test1");
},
crossDomain: true,
success: function(SOAPResponse) {
alert('ok');
},
error: function(SOAPResponse) {
alert('no ok');
}
});
And my service:
public string Test()
{
try
{
return "Successfull!";
}
catch (Exception ex)
{
return ex.Message;
}
}
I spended many many times to search and try many solutions but it not working.
Can anyone help me?
I suppose your data type can be XML, not a problem there. Question is, how do you encode your data or parameters? Perhaps check the response in the POST request in the console of your browser.
I picked up a few things in c# to enable this automatically which is nicely documented here:
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Then one thing left to do was to JSON.stringify() the data. So bhRequest is a json object right?
... and then cross browser you'll have to implement json2.js:
https://github.com/douglascrockford/JSON-js
I don't see where your var named soap is being used. It looks like it should be the "data: " that's being sent to the SOAP service, but there's something called bhRequest there instead.
Also make sure you're allowing Phonegap access to your remote server with
<access subdomains="true" origin="*" />
in your config.xml. When you get things working you can make it more restrictive by limiting it to your icafe.ipos.vn domain.

$.ajax and .each in JQuery, with MVC, isn't asynchronous

my Ajax calls don't seem to be asynchronous when wrapped inside a .each loop, instead they seem to wait for each to finish before calling the next one ..
MVC C#:
[HttpPost]
public JsonResult DoActionGetNextStep(JSONSubmission Submission)
{
SomeStruct body = new SomeStruct();
DateTime start = DateTime.Now;
try
{
System.Threading.Thread.Sleep(5000);
body.html= "There, done";
}
catch (Exception e)
{
body.html= "There was an error: "+e.Message;
}
TimeSpan s = DateTime.Now - start;
ast.Html = body.html+ "<p> c# took " +s.Seconds +"s</p>";
return Json(body);
}
JQuery:
function DoActions(targets) {
$(targets).each(function () { DoAction($(this)); });
}
function DoAction(target) {
var parent = $(target).parents('div.actionReplaceable');
var JSONSubmission = { Data : "somedata" };
var Submission = JSON.stringify(JSONSubmission, null, 2);
$.ajax({
type: 'POST',
url: '/Main/DoActionGetNextStep',
data: Submission,
async: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (Result) {
var html = Result.html;
$(parent).html(html);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$(parent).html("JQuery Error: " + textStatus + "\n" + errorThrown);
}
});
}
This ends up taking 25 seconds for 5 elements, each of them reporting that their call took 5 seconds. I thought ajax calls were asynchronous, so this operation should take 5 seconds total? Both server and browser are running on my localhost. Can anyone spot what I'm missing?
There are two reasons why Ajax calls aren't processed in parallel:
Most browsers limit this, either because they only use two connections to each site they contact or because they explicitly limit concurrent Ajax calls.
If you access the session state in an ASP.NET application (MVC or not), you'll also run into an exclusive lock that causes parallel connections to wait. For MVC, there's an attribute to indicate that your controller action only requires read-only access to the session state to work around that.
Your requests should be asynchronous. Check with console.log in the appropriate places to see when things happen.
$(targets).each(DoAction);
function DoAction() {
var $parent = $(this).parents('div.actionReplaceable'),
JSONSubmission = { Data : "somedata" };
console.log("sending request for " + this-id);
$.ajax({
type : 'POST',
url : '/Main/DoActionGetNextStep',
data : JSON.stringify(JSONSubmission, null, 2),
contentType : 'application/json; charset=utf-8',
success : function (Result) {
console.log("received response for " + this-id);
$parent.html(Result.html);
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
console.log("received error for " + this-id);
$parent.html("JQuery Error: " + textStatus + "\n" + errorThrown);
}
});
}
There is no need for a target parameter. jQuery sets this correctly for callback functions.
Once you got rid of the target parameter you just need to pass the function reference to .each().
Unless the return type is JSON (seems to be HTML here), setting dataType: 'json' is wrong.
setting async: true is superfluous unless you configured the global Ajax options to be async: false. Which I hope you did not.

unable to pass post value over from ajax to the page in .net c#

Does anyone know what is it going on here? I have try to pass a value from ajax to .aspx, but somehow the value seem doesn't pass over successfully.
Following is my code:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: "sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
and this is my code inside my .net c#:
newTest.Value = Request.QueryString["sState"];
Somehow the for Request.QueryString["sState"] is empty in .net c#. Does anyone know what is going wrong here ?
When passing data in POST, the data is not passed in Request.QueryString, it's passed into Request.Form instead. Try
newTest.Value = Request.Form["sState"];
Another thing I'd change is the jQuery call - use a data object instead of just a string, a such:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: { sState: "VIC" },
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Request.QueryString is for GET requests only. For POST requests, you need Request.Form. See also: Get POST data in C#/ASP.NET
You need to use GET request as it is light in nature but less secured too and it is passed in querystring.:
$.ajax({
type: "GET",
url: "pgtest.aspx?sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Now you will get below values:
newTest.Value = Request.QueryString["sState"];

Ajax post error

I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.

Categories