I want to open a html page when user presses a function key.
Now the capturing of the function key works fine, but the logic to open the appropriate page is written in Code-Behind of master page.
I read on internet that if I want to call function in code behind then I have to create a web- service and call the webservice method from master page.
But for some reason this is not working.May be I am not calling the web service properly.
Can some body please help?
Many Thanks
<cc1:ToolkitScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release" EnableHistory="true" EnableSecureHistoryState="false"
EnablePageMethods="true" CombineScripts="false">
<Scripts>
<asp:ScriptReference Path="~/ShowHelpPage.asmx" />
</Scripts>
</cc1:ToolkitScriptManager>
document.onkeydown = function(event){
if(window.event && window.event.keyCode == 113)
{
window.open("HelpFile/index.html");
}
else if(event.which == 113)
{
window.open("HelpFile/index.html");
DisplayHelpFile();
}
}
function DisplayHelpFile()
{
var i = PageMethods.DisplayHelpPage();// I think this is wrong
alert(i);
}
Web Method
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ShowHelpPage : System.Web.Services.WebService
{
[WebMethod]
public string DisplayHelpPage()
{
return "Window.Html";
}
}
"I read on internet that if I want to call function in code behind
then I have to create a web- service and call the webservice method
from master page"
I assume in the context you are refering to methods and not functions. Do you want to call a method when you master page loads? I would think that you dont need to create a Web Service for this? Unless you want the client to initiate the request through Async and you are using JavaScript and AJAX to make the request. What are you trying to achieve? It seems to me this can be achieved through just javascript. If you call a page through JavaScript it should load itself?
Below achieving what you want but using just javascript.
function keyHandler(e)
{
... key handling script
if(myKey == 'F1')
{
window.location.href = '...';
}
}
document.onkeypress = keyHandler;
If you need to call this Web Service and it needs to be initiated from the Client you could use JQuery to do this. Use the same approach with ShowHelpPage.asmx storing the processing and your rendering handled through JavaScript. This also to the best of my knowledge removes the dependency on ToolkitScriptManager.
function DisplayHelpFile()
{
$.ajax({
type: "POST",
url: "ShowHelpPage.asmx/DisplayHelpPage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(result)
{
alert(result);
}
},
error: ErrorMessage
});
function ErrorMessage(result)
{
alert(result.status + ' ' + result.statusText + ' ' + result.responseText);
}
}
Your web method needs to be static.
Related
I want to offer a user discount (pop up) after 30 seconds being on site (any page). Since this project implements WebForms master page, I put the timer inside Master.aspx, and the method that communicates with db inside Master.cs. The method checks eligibility through calling stored procedure, and returns bool.
I set javascript timer inside aspx Master page, so after the time out, I want to call the method providing it userID. How can I call this isUserEligibleForDiscount method that's inside Master.cs using javascript?
setTimeout(function () {
if (sessionStorage.getItem('timer') == 'on') {
if (isUserEligibleForDiscount(userID)) {
$('#myModal').modal('show');
}
sessionStorage.setItem('timer', 'off');
}
}, 30000);
Use [WebMethod] attribute. It makes the method callable from remote Web clients (WebMethodAttribute Class).
Decorate your isUserEligibleForDiscount with that attribute.
You can then call the method via Ajax. You specify your page in the URL for the Ajax call: 'yourpage.aspx/isUserEligibleForDiscount'
You can put your method(s) into a page that does nothing but hold code, or you could call an asmx web service.
setTimeout(function() {
doAjaxPageMethodCall();
//if (sessionStorage.getItem('timer') == 'on') {
// if (isUserEligibleForDiscount(userID)) {
// $('#myModal').modal('show');
// }
// sessionStorage.setItem('timer', 'off');
//}
}, 3000);
function doAjaxPageMethodCall() {
$.ajax({
type: "POST",
// page-methods.aspx holds your methods.
// replace AjaxPageMethodCall w/ isUserEligibleForDiscount.
url: "/page-methods.aspx/AjaxPageMethodCall",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(data) {
if(data.d===true) {
// show modal .
}
}).fail(function() {
$("#lbl").html("Houston...");
});
}
Of course you can combine the 2 functions, they're just split up for testing.
Web service is similar:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="/web-services/test-service.asmx" />
</Services>
</asp:ScriptManager>
And the only change to the ajax call is the url:
url: "/web-services/test-service.asmx/HelloWorld", ...
Your test-service.cs file will hold the actual methods.
I am having an javascript function for a HTML img click event in aspx page. And a server Method in its code behind page.Now I want to call the server method from the javascript function without any parameter only when the HTML img is clicked by the user.
C# Code Behind Method:
[WebMethod]
public void PopUpClick(object sender, EventArgs e)
{
//Something;
}
JavaScriptMethod:
$(document).ready(function () {
$('.clickme').click(function () {
PageMethods.PopUpClick();
});
});
Also I added into the master page: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />
It is not working.When I debugging this Javascript function on the Chrome
I saw an error:Uncaught Reference Error:PageMethods is not defined.
.aspx
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
JavaScript
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
C#
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
The WebMethods that are defined must be "static".
The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!!
$.ajax({
type: "POST",
url: 'GenerateEAInHtml.aspx/GetAllRegions',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
The WebMethod is defined this way:
[WebMethod]
public static List<Region> GetAllRegions()
{
/* Your Code goes here */
return regions;
}
You might want to use this Ajax Post to also pass JSON data to the WebMethod by passing the data parameter!! This should help.
Assumption that your page name is abc.aspx and xyz is the function name that you have to call.
javascript :
function sendData(offset) {
$.ajax({
type: "POST",
url: "abc.aspx/xyz",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Server Side : add Imports System.Web.Script.Serialization
WebMethod(enableSession:=True) _
Public Shared Function xyz() As String
your code here
End Function
Add module in web.config -> system.webServer
->system.webServer>
->modules>
->add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
->/modules>
->/system.webServer>
Back end C# code is separate from your front end JavaScript code. JS runs on the client side and C# runs server side. In order to have front end code fire off a back end functions, you would either need your function to do a form postback or use Ajax (or an equivalent) to call that pages function.
Try this
[WebMethod]
public static void PopUpClick(object sender, EventArgs e)
{
//Something;
}
Use an ImageButton. The handler does not need to be tagged as [WebMethod]
<asp:ImageButton runat="server" ID="btnPopUp" ImageUrl="img.png" OnClick="PopUpClick" />
Why do you want to use img directly?
There is a line at the top that says uncomment this to call it by JavaScript.
Uncomment that.
Then also add a [ScriptMethod] to your method like this:
[WebMethod]
[ScriptMethod]
public void PopUpClick(object sender, EventArgs e)
{
// Something;
}
You should then be able to call it from the PageMethods object.
However I've just done some research and it seems that you may need to place your code that uses PageMethods at the end / after the ScriptManager as its possible you are trying to use PageMethods before its been declared in the JavaScript. Alternatively if you're using jQuery then you can do it in the ready event so you know the page and everything has loaded. I think this will probably turn out to be the root cause.
A web method has to be declared as static and public.
Although you can't access the page directly, you can either pass what you need into the web method from the call in your client side code, or store what you need in session or a similar state storage mechanism that is accessible from your static web method.
That may require re-thinking what you're trying to do with it.
I am building a Multi-Lingual site in webforms aspx project, and I am thinking of the best solution to do this.
I have some images on the MasterPage, and once clicked, I am calling a Jquery method, that should redirect to a web method.
In turn I have a base page that is initializing the Culture, and all the pages, except for the MasterPage are inheriting from it.
So far I have the following:-
HTML:-
<div class="LocalizationFlags">
<img src="Images/gb.png" onclick="langSelection('gb')" />
<img src="Images/fr.png" onclick="langSelection('fr')"/>
<img src="Images/es.png" onclick="langSelection('es')"/>
<img src="Images/de.png" onclick="langSelection('de')"/>
<img src="Images/it.png" onclick="langSelection('it')"/>
</div>
JQuery :-
function langSelection(lang) {
setSession(lang);
};
function setSession(Lang) {
var args = {
lang: Lang
};
$.ajax({
type: "POST",
url: "Site.Master.aspx/SetUserCulture",
data: JSON.stringify(args),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('Success.');
},
error: function () {
alert("Fail");
}
});
};
Site.Master.cs
[WebMethod(EnableSession = true)]
private void SetUserCulture(string lang)
{
HttpContext.Current.Session["CurrentUI"] = lang;
}
BasePage.cs
protected override void InitializeCulture()
{
if (Session["CurrentUI"] != null)
{
String selectedLanguage = (string)Session["CurrentUI"];
UICulture = selectedLanguage;
Culture = selectedLanguage;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(selectedLanguage);
}
base.InitializeCulture();
}
Now there are several problems with what I have at the moment. Jquery does not work, throws a "Fail", and also I know that I cannot use the Site.Master.cs to put the webmethod in.
Is it just a case of creating a WCF service for this method, and then calling it from the Jquery code?
Am I on the right track here?
Thanks for your help and time
Your ajax request most likely fails because it does not reach the destination - as you said you cannot have WebMethod in the master's codebehind. Also there is no need to serialize your parameters with JSON, plain object should work just as well. Besides, dataType: json is not needed here - you do not return any data for this request.
There is no need for a web service here - a simple HTTP handler will suffice. Just do not forget to implement marker interface IRequiresSessionState to have an access to the session inside the handler.
In general cookies might be a better place to store user's culture, since you might want to retain this information across different visits of the same user. Another option is also user profile in the DB - in case you are dealing with registered users. However your current implementation that uses session should work.
I have created a web service in C# and now need to call it from a mobile app. I'm trying to create a Windows 7 mobile app, but using HTML5 and Javascript not the native code. The web service takes 2 parameters, Email and Password, and returns a Dataset. I don't really have any javascript experience (or web services experience for that matter, trying to learn with this project), and when trying to research how to call a web service using javascript I just found too much information and didn't know where to begin because so many other technologies were also mentioned.
So I decided to try things out and this is what I came up with so far:
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
}
function LoginButton_onclick() {
UpdateChildrenApp.PhoneWebServices.GetMyChildren(document.getElementById('EmailBox').value,document.getElementById('PasswordBox').value, OnComplete, OnError)
}
function OnComplete(result) {
for (var i = 0; i < result.tables[0].rows.length; i++)
document.getElementById('Test').innerHTML += ''+(result.tables[0].rows[i].col_name);
}
function OnError(result) {
document.getElementById('Test').innerHTML ='Error :'+result.get_message();
}
</script>
This code does nothing when I press the submit button. Could someone please point out what the problems are and how I can fix them or suggest what I should research to address the problems and put me on the right track? Any help is greatly appreciated.
First, your webservices should return a JSON object if you want to use it in javascript.
You can of course return any XML/string, but using JSON will be A LOT easy to use the data in javascript.
Then, I would advise you to use jquery to call the webservice, as jquery will do a lot of work for you.
Read this article, it should help you set different components correctly:
I would use jQuery to do this kind of thing.
The ajax functionality its provides is really easy to use.
I would use the Revealing Module Pattern (RMP) and 2 javascript files. If you're unfamiliar with the RMP, there is a great post covering it here:
http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx
I find that if I dont employ some kind of structure to my js code using the RMP, I just end up with a mess of functions in one file.
Id have Startup.js and Dataservice.js and they would look something like this:
Startup.js
var Startup = function () {
var isValid,
dataObject = {},
populateDataObject = function () {
dataObject.dealer = $("[id$='_txtUser']").val();
dataObject.password = $("[id$='_txtPassword']").val();
},
init = function () {
var dealerId = 0;
$("[id$='_SubmitButton']").bind('click', function (evt) {
evt.preventDefault();
populateDataObject();
if (isValid) {
Dataservice.processLoginRequest(dataObject, processLoginRequestResult);
}
});
};
return {
init: init,
processLoginRequestResult: processLoginRequestResult
};
} ();
Dataservice.js (assumes old school .asmx, change as needed)
var Dataservice = function () {
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
var serviceBase = '../services/LoginService.asmx/',
processScreenRequest = function (valObject, callback) {
$.ajax({
url: serviceBase + "ProcessLoginRequest",
data: JSON.stringify(valObject),
success: function (json) {
callback(json);
}
});
};
return {
processScreenRequest: processScreenRequest
};
} ();
and then I would include refereces to these 2 js files as well as jquery in my html page.
I hope this helps.
I've used Dojo for this once, its pretty simple you can make xhrget or xhrpost requests. It has a function called load that is the callback where you can modify the contents of the HTML components in the page.
Use these links : http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html
Is it possible to retrieve value or date from calling a webmethode from javascript, here is a sample code:
//This method is in a webservice.asmx file.
[WebMethod]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{
return Cities.GetAllCitiesByCountry(CountryID: countryID);
}
<script language="javascript" type="text/javascript">
function fillCities() {
var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>');
var selectedIndex = dropDownList.selectedIndex;
var value = dropDownList[selectedIndex].value;
WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, "");
}
function onSuccess(result){
alert(result[0].(PropertyName));
}
The variable x doesn't retrieve anything and I guess that it produce an error. I have tried to define an array but still it didn't work. Any idea ?
Edit:
The above code have been altered and is now an answer to my question along with the answer below which used JQuery.
Use Json response with Jquery, Its realy cool and easy.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class CitiService : WebService
{
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{
List<tbl_City> cities = GetCities(countryID);
JavaScriptSerializer js = new JavaScriptSerializer();
var jsonObj = js.Serialize(cities);
Context.Response.Clear();
Context.Response.Write(jsonObj);
Context.Response.End();
}
}
on ASp.net page
<script language="javascript" type="text/javascript">
$.ajax({
url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>',
dataType: "json",
data: "{countryID:'100'}",
success: function (result) {
alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid
}
});
you can do this easily with JQuery and ASP.NET webmethods Encosia
You need to register your web service with ScriptManager and then call it from the client side. Take a look on this tutorial:
Client-Side Web Service Calls with AJAX Extensions
Also you can use web service with jQuery but in this case you need to switch to JSON: Calling ASMX from jQuery