I have a web method in my code behind:
[System.Web.Services.WebMethod]
public static string GetStateData(string state)
{
//this is where i want to call a javascript method "GetItems"
}
I have a javascript method that retrieves some values for me and I want to get use one of those values in my web method
function GetItems() {
var variable1= $("#<%=Item1.ClientID %> input:checked");
var variable2= $("#<%=Item2.ClientID %>").val();
return [variable1.text(), variable2.val(), variable2];}
I've searched for ways to call the javascript method from the web method but every time my search results in how to call a web method from javascript.
I did find this but it was done from the code-behind of a silverlight project and when I tried adding the correct reference to my code-behind it wasn't there
var result = HtmlPage.Window.Invoke("GetItems");
Is there a reference I'm missing?
Thanks for your response
You can't do that. Your calling a webmethod through AJAX. your sending small pieces of information to a static method on the server that knows nothing about the specific page object (That isn't static).
What you want to do is send those values and data in the AJAX call to the webmethod. Your not making a full postback so you know nothing about the current state of the page except what you pass as paramaters to the webmethod.
Either send the information in the first place or return with some kind of flag when you want the information and get the client to make an ajax call back to another function with the information and let it continue from there.
Instead of trying to call javascript from a webmethod use the return value of the webmethod to decide what javascript function to call.
Calling javascript from a webmethod is not possible as far as I know - you need to understand the distinction between server side and client side code.
Related
First off, I'm using static html and javascript and C# Web API.
So I have a link that calls an oauth2 server, on my html file, say index.html
Now is it ok to set the callback page to index.html
It seems to work, and it gets sent to index.html?code=125f0...
Is this ok to do or do I need a seperate callback page. Is code, the token?
Now how should I consume this?The javascript doesn't seem to get hit on the call back.
Edit, actually, the javascript seems to get hit on the call, back but I'm not getting anything undefined from:
$(function () {
var params = {},
queryString = location.hash.substring(1),
regex = /(^&=]+)=([^&*])/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if (params.error) {
if (params.error == "access_denied") {
sAccessToken = "access_denied";
//alert(sAccessToken);
}
} else {
sAccessToken = params.code;
alert(sAccessToken);
}
});
Also, can my callback page be a C# web api call? And send the token that way. I'm guessing no, cus then you'd never know what user agent is sending it, and couldn't communicate back unless you somehow passed a id and used signalR? It seems better to get it in javascript and send the token to web api. But then can web api make calls to the resource if it has the token?
sorry, I'm still learning
OAuth2 has various "profiles". The "Authorization Code Grant" flow (what you are using) requires a server side component that exchanges the code for token.
Single Page Applications, typically use the implicit flow. See here for a quick description: https://docs.auth0.com/protocols#5 (ignore references to "Auth0", the underlying protocol is the same regardless of the implementation).
See here for a more thorough description of both flows: What is the difference between the 2 workflows? When to use Authorization Code flow?
Sorry, it was sorta of strange question and bad wording. But what I ended up doing is making an HTML callback page which takes in the code. I popup the OAuth2 server page in a window then it calls my callback page. Then my callback page will close the window and pass the code back to my parent page.
I'm trying to invoke javascript from C# in my project, I want to call a javascript function that I've defined with parameters but I'm stuck on how to do it.
MainPage.xaml has this my:CordovaView that wraps my phonegap project, but I'm a little lost on how to "inject" and run javascript into it.
Has anyone done this? I'm trying to do push messages
I haven't done this with cordova per se, but in general you just need to remember where the code is executing. The C# code is executing on the server, and the javascript is executing on the client, so, you want your C# to emit a value that can be consumed by the client.
The following javascript snippet is based on Razor engine syntax, hopefully it's enough to get you started.
function alertVar(someVal) {
alert("JS, someVal = " + someVal);
}
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("#Model.ServerValueForClient");
});
This is the html that that the server would send to the client after interpolation (assuming that somewhere on the server you set the value #Model.ServerValueForClient = "set by the server";)
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("set by the server");
});
HTH
Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.
I have a web page with JavaScript that calls C# methods using jQuery and AJAX. This works fine. I would like to know how to call JavaScript functions from the C# code, if this is even possible. If it's not possible, is there a sane alternative?
Assuming the browser initiates the interaction
In general, your server-side C# code will respond to interactions initiated by your client-side code. If you're looking for ways your C# code can initiate the interaction in the absense of a browser request, see the next section below.
If you're processing a full page response, then of course you can just output script tags containing the call you want to have occur. Make sure that the script is making the call after the function it's calling has already been defined by an earlier script tag, and if there's going to be DOM interaction be sure to put that script at the bottom of the page (or use jQuery's ready feature).
Responding to Ajax calls, it's possible for the C# code to return strings containing JavaScript code, which your in-page code would then execute (e.g., via eval or similar), but it's generally best to avoid that.
Instead, have the C# code return data in response to an Ajax call, and have your in-page code respond to that data by calling the appropriate function.
A bit of a hybrid of the two is to have your C# code return data that indicates what function to call and what arguments to supply to it, and to have a map of your functions that you index into with the function name, e.g.:
var functions = {
foo: function(arg0, arg1) {
alert("foo called with " + arg0 + "," + arg1);
},
bar: function(arg) {
alert("bar called with " + arg);
}
};
$.ajax({
url: "/path/to/resource",
dataType: "json",
success: function(data) {
if (data && data.fname && data.args) {
functions[data.fname].apply(undefined, data.args);
}
}
});
There, your C# code would return a string containing information encoded in JSON as an object with an fname property (a string giving a function name) and an args property (an array of arguments to pass to the function), which jQuery will deserialize into an object for you. Then we look up the function object in the map using its name (functions[data.fname]) and use the built-in Function#apply to call it and pass in the arguments. That works because you can refer to JavaScript object properties using either dotted syntax and a literal for the property name (obj.propName = 42), or using bracketed syntax and a string for the property name (obj["propName"] = 42), where in the latter example the string can be any expression, including a variable or property reference (name = "propName"; obj[name] = 42;) — which is how we're looking the functions up on the functions map.
I'm not suggesting you do that, just saying it's possible.
If you're trying to have the server initiate the interaction
If you want the server to reach out to the browser instead, you'll have to have some channel of communication established between them, either using the new (and variously supported) web sockets API, or various Comet techniques.
Javascript function can not called directly from C#, rather Javascript function/code block can register with page from C# code behind which is called after render or called when it is necessary.
//Register Script block for JS code
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptBlockKey",
"<script> alert('JS alert written in C# code behind.');</script>", false);
//Register Script block for calling JS function
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptBlockKey",
"SomeJSFunction();</script>", false);
I want to call two functions on same event 1 is client side and other 1 is server side.
How can i do that
<input type="text" ID="txtUserName" runat="server" maxlength="50"
class="DefaultTextbox" style="width:180px;" value=""
onfocus="ControlOnFocus('', this, spanUserName);"
onblur="ControlOnBlur('',this, spanUserName); "
/>
onblur="ControlOnBlur(); function2();
Is it correct ?
onblur="ControlOnBlur(); function2();
Thats correct. Actually it's not very good practice to define events inlined in HTML but it works. Everyhing between " and " in onblur="" is treated as one long JavaScript code block so you could write anything in it, even your whole program if you would like.
onblur="sentence1; sentence2; sentence3;"
If using web forms, you want to post back to the server to process a server-side event, you can use __doPostBack(this.name, '') to post back to the server (it was mentioned alternatively that you can use a server side event to output (GetClientResourceUrl I believe or named similarly) this, but I like to use the __doPostBack method to perform the postback.
If using MVC, you can invoke an action method using $.get or $.post as in $.get("/Controller/Action", function(result) { }). For web forms, you can't invoke a method directly. You can invoke a web service or page method.
HTH
The closest you can get is calling a local function (javascript), and then firing off a request to the server via an asynchrounous call (Ajax). You cannot directly call a method on the server from the client though.
Using jQuery, it would look like this:
$("#txtUserName").blur(function(e){
ControlOnBlur(); // call first function
$.post("/methods", {methodName:"refreshData", function(results){
/* results represents that which was returned from the server */
alert(results);
});
});