Why my CallBack function doesnt works? - javascript

I'm trying to make some calls to a WebService
I did exactly what is described in this article
http://viralsarvaiya.wordpress.com/2010/03/23/calling-web-service-from-java-script-in-asp-net-c/
Looking at the console of firebug I could see that my function was executed and returned the expected data, but my callback functions (OnComplete, OnError, OnTimeOut) are never executed.
Whats wrong?
Here is the code (same code of the article)
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://Localhost...xys/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[System.Web.Script.Services.ScriptService()]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(string strNoOfData)
{
return strNoOfData;
}
}
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function CallService() {
Service.HelloWorld(document.getElementById('Textbox1').value,
OnComplete, OnError, OnTimeOut);
}
function OnComplete(Text) {
alert(Text);
}
function OnTimeOut(arg) {
alert("timeOut has occured");
}
function OnError(arg) {
alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Call Service" OnClientClick="CallService()" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

The problem was the project type, it works in WebApplication, not in WebSites

Im a VB guy mostly so ....
Try one at a time in order.
First see if you are really selecting the textbox, I doubt it. Set the ClientIDMode to be static.
Second try [WebMethod(), ScriptMethod(ResponseFormat:=ResponseFormat.Json)]
Third make the method static .. oops virtual and the class also.

Related

How to call an asp control using getElementById() in a javascript function that is included in ScriptManager.RegisterStartupScript

I'm required to use ScriptManager.RegisterStartupScript to run a javascript function while using asp.net's update panel.
My goal is to run my javascript function named Top10 with json parameter called jsonTable, in this function everything is working well aside from var hfield = document.getElementById("<%=hf.ClientID%>"); which is supposedly get the asp.net's hiddenfield control but it keeps returning null.
I reduced the code so that I can get to the point.
c#:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
dtCurrentTop1O = dsCurrentTop10Winners.Tables["Top 10 Winners"];
string strCurrentTop1O = serializer(dtCurrentTop1O);
ScriptManager.RegisterStartupScript(this.updatePanel1, GetType(), "Javascript",
"javascript:Top10(" + strCurrentTop1O + ");", true);
}
}
Markup:
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="head">
<title></title>
<script src="Scripts/Top10.js" type="text/javascript"></script>
</asp:Content>
<asp: Content ID="Content2" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp: ScriptManager ID="scriptManager1" runat="server"></asp: ScriptManager>
<asp: UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<asp: Panel ID="Panel1" runat="server">
<asp: HiddenField ID="hf" runat="server" />
</asp: Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
javascript: Top10.js
function Top10(jsonTable) {
var chartImg;
var hfield = document.getElementById("<%=hf.ClientID%>");
};
According to your description, the function you're calling is located in the file 'Top10.js'. AFAIK, ASP.NET won't resolve definitions like "<%=hf.ClientID%>" outside of ASP.NET specific files - .js files are delivered to the webclient 'as is' (static content) and not rendered server-side like .aspx files. You'll be able to confirm this when looking at the delivered source in your browsers dev-tools.
You could either place the javascript code directly inside your markup so that the ClientId will be resolved, add an additional hiddenFieldId-parameter to the TopFiveOutsagesCurrentLC function or directly set the HiddenFields content in your Page_Load method.
Example for direct js code in Markup:
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="head">
<title></title>
<script type="text/javascript">
function TopFiveOutagesCurrentLC(jsonTable) {
var chartImg;
var hfield = document.getElementById("<%=hf.ClientID%>");
};
</script>
</asp:Content>
<asp: Content ID="Content2" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp: ScriptManager ID="scriptManager1" runat="server"></asp: ScriptManager>
<asp: UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<asp: Panel ID="Panel1" runat="server">
<asp: HiddenField ID="hf" runat="server" />
</asp: Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
I've answered my question by finding the hiddenfield control and then added it to parameters for the javascript function.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
HiddenField hf = (HiddenField)this.updatePanel1.FindControl("hf");
dtCurrentTop1O = dsCurrentTop10Winners.Tables["Top 10 Winners"];
string strCurrentTop1O = serializer(dtCurrentTop1O);
ScriptManager.RegisterStartupScript(this.updatePanel1, GetType(),
"Javascript",
"javascript:Top10(" + strCurrentTop1O + ","+hf.ClientID+");", true);
}
}

Cannot get filename from AjaxFileUpload using javascript and asp.net

I've tried solving this out and researching for weeks and i still can't get it to work. My code is to simply upload images and then save it in the database without postback.
As of now, I used AjaxFileUpload to upload images. My plan was to get the uploaded filename in AjaxFileUpload using javascript and then store it in a hiddenfield. And then when the admin clicks submit, it will get the value that was stored in the hiddenfield and then save it in the database(using the query that i have created in my code-behind).
The problem is, it will always return empty. I hope you guys can really help me on this one.
Here is the code for the aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="CreateBrands.aspx.cs" Inherits="Pages_CreateBrands" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="asp"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Music Store</title>
<script src="../Javascript/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="~/Styles/jquery.bxslider.css"/>
<link rel="shortcut icon" type="image/png" href="~/Images/rockSign.png"/>
<script type="text/javascript">
function abc() {
var elem1 = document.getElementById('<%# itemFileUpload1.ID %>').value;
document.getElementById('HiddenInput1') = elem1;
var elem2 = document.getElementById('<%# itemFileUpload2.ID %>').value;
document.getElementById('HiddenInput2') = elem2;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="wrapper">
<h1>Item Image1:</h2>
<br />
<asp:AjaxFileUpload ID="itemFileUpload1" runat="server"
Width="300px" OnUploadComplete="itemUploadImage1"
OnClientUploadComplete="abc"/>
<input type="hidden" id="HiddenInput1" name="HiddenInput" value="" />
<h1>Item Image2:</h2>
<br />
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server"
Width="300px" OnUploadComplete="itemUploadImage2"
OnClientUploadComplete="abc"/>
<input type="hidden" id="HiddenInput2" name="HiddenInput" value="" />
<br/>
<asp:Label ID="lblResult2" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" CssClass="submitButton"
Text="Save Item" OnClick="Button1_Click"/>
</div>
</form>
</body>
</html>
And here is the code for the aspx.cs:
protected void itemUploadImage1(object sender, AjaxFileUploadEventArgs e)
{
string filename = Path.GetFileName(e.FileName);
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
protected void itemUploadImage2(object sender, AjaxFileUploadEventArgs e)
{
string filename = Path.GetFileName(e.FileName);
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
string item_image1 = Request.Form["HiddenInput1"];
string item_image2 = Request.Form["HiddenInput2"];
ConnectionClassGuitarItems.AddStringInstrumentItems(item_image1,item_image2);
lblResult2.Text = "Upload successful!" + item_image1 + " and " + item_image2;
ClearTextFields2();
}
catch (Exception ex)
{
lblResult2.Text = ex.Message;
}
}
Notice the the Button1_Click, I try to access the value of HiddenInput1 and HiddenInput2 but it seems like they are empty.
Why not use a regular asp:FileUpload control and wrap part of your form/code block in an updatepanel to achieve the same desired action as using a AjaxFileUpload control:
<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPnlName">
<ContentTemplate>
<asp:FileUpload runat="server" ID="fileImport" CssClass="form-control"/>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void btnUpload_OnClick(object sender, EventArgs e)
{
if (fileImport.HasFile)
{
UploadProcessFile();
}
}
private void UploadProcessFile()
{
var fileName = fileImport.FileName;
//Process the rest of your code below you can also assign the file name to your textbox.
}
You can get your image name like this on aspx file on
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server"
Width="300px" OnUploadComplete="itemUploadImage2"
OnClientUploadComplete="abc"/>
use this script
function abc(sender, args) {
var Imagename = args.get_fileName();
alert(Imagename );
}
this way is very simple hope this help you

Add client side handler from content page to master page control

I have a requirement for four similar pages in an ASP.Net webforms application. All four pages will have a header with a dropdown and two buttons. I intend to use a master page for this header and then content pages for each of the different pages I need to produce. My master looks like this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Processing.master.cs" Inherits="MyProject.Processing" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="../../Stylesheets/Processing.css" type="text/css" rel="stylesheet" />
<script language="javascript" src="../../Scripts/js/Processing.js" type="text/javascript"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="ProcessingForm" height="100%" runat="server">
<asp:Label ID="titleLabel" runat="server" class="bold"></asp:Label>
<asp:Label runat="server" ID="storeLabel" Text="Store:" />
<asp:ObjectDataSource runat="server" ID="storesDataSource" TypeName="MyProject.Processing"
SelectMethod="GetStoresDataSource">
<SelectParameters>
<asp:QueryStringParameter Name="UserName" QueryStringField="eUserName" DefaultValue="" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:DropDownList runat="server" ID="storeDropdown" AutoPostBack="true" OnSelectedIndexChanged="storeDropdown_SelectedIndexChanged"
AppendDataBoundItems="true" DataSourceID="storesDataSource" DataTextField="Display"
DataValueField="Number">
<asp:ListItem />
</asp:DropDownList>
<asp:Button ID="refreshButton" runat="server" Text="Refresh" OnClick="refreshButton_Click" />
<%-- ************************************************************************************--%>
<%-- This is the button that I want to add client side behaviour to from my content pages--%>
<%-- ************************************************************************************--%>
<asp:Button ID="processButton" runat="server" Text="Process" OnClick="processButton_Click"
OnClientClick="DoStuff();" />
<asp:ContentPlaceHolder ID="GridDiv" runat="server" />
</form>
</body>
</html>
In the Processing.master.cs I've defined an event that the content pages can subscribe to to react when the dropdown changes:
public delegate void StoreChangedHandler(object sender, string selectedValue);
public event StoreChangedHandler OnStoreChanged;
protected void storeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (OnStoreChanged != null)
{
OnStoreChanged(sender, ((DropDownList)sender).SelectedValue);
}
}
So the content page's OnLoad contains:
protected void Page_Load(object sender, EventArgs e)
{
((Processing)Master).OnStoreChanged += StockRoomWithMaster_OnSomethingSelected;
}
void StockRoomWithMaster_OnSomethingSelected(object sender, string selectedValue)
{
this.stockReceiptGridView.DataBind();
}
What is the best way to do this same strategy for the client side DoStuff() function call that occurs when the processButton control is clicked? I could declare a global variable in the Processing.js file and in the content page assign it to a function:
Processing.js:
var processButtonClickedHandler;
function DoStuff()
{
if (processButtonClickedHandler) {
processButtonClickedHandler();
}
}
In content page:
$(document).ready(function() {
processButtonClickedHandler = DoSpecificStuff;
});
function DoSpecificStuff() {
// Custom page client side stuff
}
I think the way you are doing this is the best way. I have created created a test bu putting an alert in DoSpecificStuff in the same way you did and it worked good.

Get me off the JavaScript postback Failboat

I've got to call two js functions, setfocus on textbox and stop a postback from occuring on single buttonclick. I think I got it if I could only intercept the postback. My js skills are on par with weaksauce.
test case
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="JsTextFocus.aspx.cs" Inherits="WebApplication1.JsTextFocus" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="Javascript">
function aMethod() {
var dowork = 'bleh';
}
function setFocusOnTextBox() {
TextBox1.Focus();
return false;//Stop the postback..FAIL
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="imageBtn" runat="server" ImageUrl="images/document_Small.gif" CausesValidation="false" OnClientClick="aMethod();return setFocusOnTextBox();return false;" />
</div>
</form>
</body>
</html>
Page load shouldn't fire after OnClientClick
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("PS happened at " + DateTime.Now);
}
You are referring to TextBox1 in yout setFoucs.. function which is unknown at that point. Use document.getElementByID to get a reference to textbox and then call focus not Focus.
function setFocusOnTextBox()
{
var TextBox1 = document.getElementById("TextBox1");
TextBox1.focus();
return false;
}
You can remove the return false at the end of the Image ClientClick handler.
i.e.:
<asp:ImageButton ID="imageBtn"
runat="server"
ImageUrl="images/document_Small.gif"
CausesValidation="false"
OnClientClick="aMethod();return setFocusOnTextBox();" />

Call JavaScript in Pageload in VS2005

<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="JavaScript" type="text/JavaScript">
CheckBrow();
</script>
function CheckBrow()
{
if((navigator.appName == "Microsoft Internet Explorer") ||(navigator.appName == "Netscape"))
{
HhdnBrowsertype.value=0;
}
else
{
alert("please open the application in IE or Fire fox browser")
HhdnBrowsertype.value=1;
}
}
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:HiddenField ID="HhdnBrowsertype" runat="server" />
</div>
</form>
</body>
</html>
Here is my JavaScript function. Now I need to execute this function on page load.
Here I will check the browser type based on the hidden field value 0 or 1.
I will check this hidden field value on page load
protected void Page_Load(object sender, EventArgs e)
{
// here i need to call my javscript function
// can any one tell me the syntax
If(HhdnBrowsertype.Value==”1”)
{
// here go my page load function
}
}
Can anyone tell me how I can call this JavaScript function on page load? I am using VS 2005.
try this
<body onload="CheckBrow()">
or you can use.
Page.ClientScript.RegisterStartupScript(typeof(string), "CheckBrow", "CheckBrow();", true);

Categories

Resources