ASP.net web service using javascript to send commands - javascript

I am looking to send commands to a web service page on my local network via javascript that's being used on a WebOS tablet. Problem being is that I've never done this before and was wondering if it was even possible to do in the first place? Is it possible for me to create a VB.net to listen to a web service call/webpage?
I would be creating the "app" from phonegap using Dreamweaver. I am looking for examples of using javascript to send over a string to a web service that i can read constantly on the PC in order to preform tasks as needed depending on the button i push on the app.
So as an example:
WebOS app >
button pushed in app to call up Internet Explorer >
sends "IE" string to WS >
WS triggers the correct exec to start depending on the string sent to it (IE) >
WS sends back "OK" to WebOS app when program is launched
Does anyone have an example of something like this?
update
So i would do something like so in my javascript?:
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
function buttonClicked(str what2Pass)
{
$.ajax({
async : false, /* set as true if you want asynchronous behavior */
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:7777/WebService.asmx/PerformAction",
data: { "webOSCommand" : what2Pass},
dataType: "json",
success: function(data){
alert(true);
}
});
}
<html>
<body>
<input type="button" id="button1" value="run IE on PC" onClick="buttonClicked('IE');" />
</body>
</html>
and for my WS it would be:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Diagnostics
Imports System.Web.Script.Services
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<ScriptService()> _
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function PerformAction(byRef webOSCommand as String) As String
Dim oPro As New Process
With oPro
.StartInfo.UseShellExecute = True
.StartInfo.Arguments = "http://www.google.com"
.StartInfo.FileName = "internet explorer.exe"
.Start()
End With
Return "Started"
End Function
End Class

Yes, you can call a Web Service from Javascript via ajax. One example is this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/PerformAction",
data: { "somestring" : "IE"},
dataType: "json"
});
Your web service:
[WebMethod]
//parameter name must match the parameter name passed in from the Ajax call (sometring)
public static string PerformAction(string somestring)
{
return "something";
}
Detailed example here.

What you are doing is correct, but you need to decorate your webservice class with the [ScriptService] attribute.
[ScriptService]
public class MyWebService : WebService {
[WebMethod]
public void MyMethod() {
}
}
Once this is done you can access the web service via $.ajax like you have done.
Update
Making a slight change to your javascript function. Instead of using the 'done' method, I am setting the 'success' property of the settings object passed to the $.ajax method. If you want the webservice call to be asynchronous, you can set the async property as shown in the code below.
function buttonClicked(str what2Pass)
{
$.ajax({
async : false, /* set as true if you want asynchronous behavior */
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:7777/WebService.asmx/PerformAction",
data: { "webOSCommand" : what2Pass},
dataType: "json",
success: function(data){
alert(data);
}
});
}

Related

Web method not getting hit but ajax success says it is

Update
If I use Fiddler, I see I get a 200 OK Response but the following message:
{"Message":"Authentication
failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
I have no idea where that's coming from.
Original Post
When I place a breakpoint in the web method it is never hit. The success handler runs for the ajax call. If I change the name of the url to incorrect value, I do get an error in F12 tools that it is not found.
I've tried EnablePageMethods='true' as well on the ScriptManager.
JavaScript lives in Scripts folder
$.ajax({
type: 'POST',
url: 'Tasks.aspx/UpdateStatus',
contentType: "application/json; charset=utf-8",
data: '{ id: 8, status: 1 }',
success: function (data) {
alert('it worked!');
},
failure: function (response) {
alert(response.d);
}
});
Tasks.aspx.cs code behind
[WebMethod(EnableSession = true)]
public static string UpdateStatus(int id, int status)
{
TaskManager taskManager = new TaskManager();
taskManager.UpdateStatus((TaskStatuses)status, id);
return string.Empty;
}
I ended up changing PageMethod in the code-behind to a web service asmx file and that seemed to have worked. Now I have to figure out how to secure it.

Get json datas from C# to javascript without using [WebMethod]

I have a C# Project, and a ASP.NET project (without database).
I want to call some methods from my C# Project, get the results in JSON and use it in my javascript without using the [WebMethod], I tried to make a Controller but I'm a little bit lost.
If you have any tips it would be nice, thank you.
The code in the controller should look like:
public class HomeController : Controller
{
[...]
public virtual ActionResult GetExample()
{
[...]
var result = ...;
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public virtual ActionResult Update(MyModel model)
{
[...]
var result = model
return Json(result);
}
[...]
}
And from your java script file you make an ajax call:
$.ajax({
url: "<path>/Home/GetExample",
type: "GET",
dataType: "json",
cache: false,
success: function (html) {
[...]
}
})
or:
$.ajax({
url: "<path>/Home/Update",
type: "POST",
dataType: "json",
data: $(#my-form).serialize(),
cache: false,
success: function (html) {
[...]
}
})
I don't have enough reputation so adding my comments here. You probably want to use Web Api here which is the reason you created controller. You probably need to refer Web Api site which will help you build controllers and expose interface to be called from javascript.
Web API

Send request to server side on the text using asp.net

I want to send request on server side onFocus event but my method is not calling, really confused, tried jquery ajax for that but all failed is there any other possible way to send request on server side using asp.net textbox onFocus event?
asp.net website project is created for work.
Ajax method code
$.ajax({
type: "POST",
url: "About.aspx/GetRes",
data: "{}",
contentType: "application/text; charset=utf-8",
dataType: "text",
success: function (msg) {
alert(msg);
}
});
Method which is calling
Public Function GetRes() As String
Return "I am calling GetRes method"
End Function
If you are able to access the supplied url via browser properly then please try this..
$.ajax({
type: "POST",
url: "About.aspx/GetRes",
dataType: "text",
success: function (msg) {
alert(msg);
}
});
Also, i'm considering that your event biding is wrapped under the document.ready callback
and make the server side method like this
<WebMethod>
Public Shared Function GetRes() As String
Return "I am calling GetRes method"
End Function
You can only call PageMethods like that.
Such methods should be static(Shared) and have the WebMethod attribute.
<WebMethod()>
Public Shared Function GetRes() As String
Return "I am calling GetRes method"
End Function

Referencing a WCF Service in the web.config file via javascript

I have an asp.net webforms website and a wcf service. I use jQuery to perform my AJAX operations to/from the WCF service like so:
$.ajax({
type: "POST",
url: "192.168.1.24/ServiceMain.svc/" + serviceName,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{}",
cache: true,
success: function (json)
{
//Success operation here
},
error: function ()
{
//Error operation here
}
});
All is fine right now. However, I want to be able to do a testing and production environment, both of which will be hosted on a different server with different IP Addresses.
Clearly, hard-coding the URL to point to the correct WCF service will become a tedious problem if left unchecked. Therefore, I was wondering what was the best approach in retrieving the WCF Service's URL. I thought about using the web.config file with something like the following:
<%=ConfigurationManager.AppSettings("SomeWCFKey")%>
However, I am not sure how to correctly reference the address in my web.config file:
<endpoint address="http://192.168.1.24/ServiceMain.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IServiceMain"
contract="ServiceMain.IServiceMain"
name="BasicHttpBinding_IServiceMain" />
Any help would be appreciated, thanks.
Hi i think you are actully want to read endpoint address that you can get by this code
private List<string> GetEndpoints()
{
var endpointList = new List<string>();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);
foreach (ChannelEndpointElement endpoint in serviceModel.Client.Endpoints)
{
endpointList.Add(endpoint.Address.ToString());
}
return endpointList;
}
Here is pont that descirpt mroe in detail : Getting WCF Bindings and Behaviors from any config source
this might also help you : Programmatically enumerate WCF endpoints defined in app.config

is there a way to set an asp.net session variable from a javascript/jquery link?

Basically i am trying to set a session when a user clicks a specific button is this possible?
So i need to set this session
Session("TenHolStDateNewCheck") = "%"
When this link is clicked
blahblah
thanks
Jamie
You need a server side code to set session, use $.ajax() function
Using jQuery with ASP.NET
You can use something like this:
Server side (C#)
public partial class _Default : Page
{
[WebMethod]
public static void SetSession()
{
...
}
}
Client side (aspx)
$.ajax({
type: "POST",
url: "Default.aspx/SetSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert('SetSession executed.');
}
});
You could do it with a ajax call to a page that sets the session variable of choice to whaterver you send along with the ajax call
See: jQquery Ajax
You can implement JSON-RPC set_session_var method and then in JQuery with $.ajax send json-rpc request to set_session_var method.

Categories