Showing posts with label button. Show all posts
Showing posts with label button. Show all posts

Wednesday, March 28, 2012

Calling jvascript function from the button under UpdatePanel

Hello,

I am having a a web application developed using asp.net2.0 with vb.net as a language.

In this web application i am having two buttons and one update panel. Now my button1 is outside the updatepanel and another button2 is present inside the updatepanel.

In asp.net if we want to run any javascript function on the click of a button then we normally use the button.attribute.add() function but if we want that when user click on button then first some server side code will be performed and then the javascript function will be called.

For that we uses the below code in asp.net !!!

Page.ClientScript.RegisterClientScriptBlock(Me.GetType,"Script", "<Script>alert('Hello');</Script>")

this code is working fine on the click event of the button that is present outside the update panel. But when i am running the same code on the click event of the button that is present inside the updatepanel then its not working,

Remeber that i d't want to run the javascript code when user just click on the button , i want first some server side code wil perform his work then after this script will run.

But for controls under update panel its not working.??

please paste your code here, because I am doing almost the same thing here without any issues.


Hi,

Add a Literal control to your web form.

In your Click method use this code:

literal1.Text = "<script type=\"text/javascript\"> alert('Hello world!');</script>";

Dont forget to clear Text property in another postbacks.


Use ScriptManager.RegisterStartupScript, instead of the ClientScript class' method.


Can anyone tell me the solution for this?

Me too getting the same issue.

Thanks,

Jasmeeta.

calling javascript function after asychronous call back event

I have a grid showing a list of records and a 'AddNew' Button on page. When user clicks on 'AddNew' a 'Table' which is not visible by default becomes visible using javascript and setting 'style.visible='visible'' and 'style.display='block'' properties. Now when user enters the data for new listing and click on 'Save Data' button i am sending an aschrounous call back using AJAX tool kit and UpdatePanel. Everything workes fine and record is entered withour complete Page Postback. But after the record is inserted and Grid is refreshed with asychronous postback what i want is to Hide that 'Add New' table and just wanted to show Grid on page. And the problem is i am not able to call the javascript function after asychronous call back which hides the Table.

Any suggestions?

Look into the Sys.WebForms.PageLoadedEventArgs class.

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageLoadedEventArgsClass/default.aspx

(its a lot easier than the docs make it look)

<script type="text/javascript">var postbackElement;Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded); function beginRequest(sender, args) { postbackElement = args.get_postBackElement(); } function pageLoaded(sender, args) { var updatedPanels = args.get_panelsUpdated(); if (typeof(postbackElement) === "undefined") { return; } else if (postbackElement.id.toLowerCase().indexOf(YOURPOSTBACKELEMENT) > -1) { //WHATEVER SCRIPT YOU NEED TO RUN } }</script>

Thankslilconnorpeterson ! your solution worked fine but fortunately i came to know that the problembecomes really simple and there is no need for calling javascript and making a Table Visible/Invisible if i replace the HTML table with server side Panel. Now i can simple make it Visible/Invisible by setting its Visible/Invsible property to true/false in codebehind.

Regards,

Zeeshan Malik

Calling ASP.NET event handler from Javascript

Does anyone know how to call an event handler from Javascript? What I am trying to do is a user clicks a button, I check to see that all the tasks are complete (from the database), if they aren't I display a confirm box saying "Should we mark all the tasks as complete?" If they select yes, I want to call a function in the ASP.NET code.

Any suggestions would be much appreciated!

Thanks,
Matt

In asp.net 1.0 and 1.1 it was

__doPostBack('myButtonID', '');

You may have to a validator on the page so that asp.net renders the javascript to handle this. You can easily put a linkbutton on with the url set to empty (or something like this).

EDIT : It gets complicated if you need the button to also do some validation. Let me know and I can try to help here.

There is a better method in asp.net 2.0 - something on a button called onBeforePostBack(). Not sure as I do not use it.


I have determined a solution to this problem. I create the "confirm" message on the server side:

string scriptCode ="if(confirm('Not all work order items have been marked as done. Would you like to mark all items as done and close the work order anyway?') == true) confirmComplete();";

as you can see, I place the confirm in an if statement that calls a javascript function on the page. The javascript function just calls the "click" event on a button I have place on the page and hidden using CSS. The action that the button takes on the server side is the action want it to take.

This brings an interesting problem. When I use the javascript function to click the button, it posts back but does not update the screen. Any suggestions now?

-Matt


Check this link

http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx

Calling a web service in a javascript causes page reload

Hey guys,

Here is what is happening. I have a user control in which I have an update panel with a button and some label. On click of that button, I call a javascript function which in turn calls a web service. The web service does get called and everything works nicely, but the whole page is being refreshed. The moment the javascript calls a web service, the refresh of the whole page occurs (when in turn nothing should happen besides the web service called).

Do I have something misconfigured that causes the script manager to do the whole page refresh on a web service call? I have the same structure in another control, and that one doesn't cause the page refresh.

If anyone has experienced this and have a solution for it, I would love to hear it.

Thanks!

Are you using Server Button Control(<asp:Button/>) of usual html button(<input type="button"> ?

I'm assuming you have something like:

<asp:Button ... OnClientClick="CallMyWebService()" />

or

<input type="button" ... onclick="CallMyWebService()" />

Try making it "CallMyWebService(); return false;"... the "return false" tells the browser not to continue handling the event (by submitting the form, for example). If that's not it, you might try showing us your code.

Calling a Web Service from Javascript

Hello!

I'm developing a WebTv channel using Atlas. My problem is in the calling of the Webservice from Javascript, it only works when I put one button like in the Atlas example:http://atlas.asp.net/docs/atlas/samples/services/Simple.aspx

The error appears when I'm invoking the WebService on the 'onload' event of the page:

requestSimpleService = iDomus.RSS..RssParser('http://www.maisfutebol.iol.pt/rss.php',OnComplete, OnTimeout);

The error on the 'onload' event is: Microsoft JScript runtime error: 'iDomus' is undefined.

I suspect that the namespace is not recognized because the Atlas engine is rendered after my script.

Any help will very appreciated.

Best regards,

Paulo Alves.

not that i have any answer for this but...

do you have "Type.registerNamespace("iDomus")" any where in your javascript?
better yet... is it before the actualy class (or object) decleration:

<script type="text/javascript">
Type.registerNamespace("iDomus");
iDomus.RSS=function(){
...
}
</script>

The other problem is that you might not have the "Namespace" setup correctly... so if your object is actually "iDomus.RSS.RssParser" then I would register the "iDomus.RSS" Namespace

since I'm working blind with what the page setup looks like...
it could also be that your object decleration is further down in the code than in the "onload" event.

again... i'm not apart of any "team" so... take it for what it is worth:
declare all of your objects first and then utilize the "pageLoad" function that gets called from Atlas

-- page declare
-- html
-- head
-- -- script manager
-- body
-- -- html elements
-- end body
-- script [for atlas]
-- -- js objects
-- -- pageLoad(){}
-- end script
-- end html

this way if you have the a seperate JS file then the "Script Manager" should load the JS file before the "pageLoad" or before the lower script section gets parsed by the browser

hope that helps...


Hellomeisinger!

Thank you for your reply.

The namespace I think is registered by the ScriptManager. When I invoque the webservice: Rss.asmx/js the result is:

Type.registerNamespace('iDomus'); iDomus.RSS=new function() { this.path = "http://localhost:4360/WebTV/RSS.asmx"; this.appPath = "http://localhost:4360/WebTV/"; var cm=Sys.Net.ServiceMethod.createProxyMethod; cm(this,"RssParser","url"); }

My aspx has the follow code:

<%

@.PageLanguage="C#"AutoEventWireup="true"CodeFile="SimpleRSS.aspx.cs"Inherits="aluno_Media_player" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>WebTV.ESTIG</title><linkrel="stylesheet"href="default.css"type="text/css"/>

</

head><atlas:ScriptManagerID="scriptManager"runat="server"EnableScriptComponents="true"><Services><atlas:ServiceReferencePath="RSS.asmx/js"/></Services></atlas:ScriptManager>

<

bodytopmargin="0"leftmargin="0"rightmargin="0"background="images/ban5.jpg"><formid="form1"runat="server"><divid="Publico"class="PainelWebTV"></div>

<

scripttype="text/javascript"language="JavaScript">//timer = window.setInterval('parser();',1000);

parser();

function parser()

{

//Call script proxy passing the input element data

requestSimpleService1 = iDomus.RSS.RssParser(

'http://www.publico.clix.pt/rss.asp?idCanal=10'

,

//params

OnCompletePublico,

//Complete event

OnTimeoutPublico

//Timeout event

);

window.clearInterval(timer);

timer = window.setInterval(

'parser();',10000);returnfalse;

}

function OnCompletePublico(result)

{

Publico.innerHTML = result;

}

function OnTimeoutPublico(result)

{

Publico.innerHTML =

"Offline.";

}

</script></form><scripttype="text/xml-script">

<page xmlns:script=

"http://schemas.microsoft.com/xml-script/2005">

<references>

</references>

<components>

</components>

</page>

</script>

</

body>

</

html>

------------------------------------------

And the WebService:

<%

@.WebServiceLanguage="C#"Class="iDomus.RSS" %>

using

System;

using

System.Web;

using

System.Collections;

using

System.Web.Services;

using

System.Web.Services.Protocols;

using

System.Text;

using

System.Text.RegularExpressions;

using

System.Xml;

using

System.Net;

using

System.IO;

namespace

iDomus

{

[

WebService(Namespace ="http://idomus/")]

[

WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]publicclassRSS : System.Web.Services.WebService

{

[

WebMethod]publicstring RssParser(string url)

{

string title =null;string link =null;XmlTextReader reader =null;StringBuilder sb =newStringBuilder();

reader =

newXmlTextReader(url);

reader.MoveToContent();

if (!reader.EOF)

{

reader.MoveToContent();

int cont = 0;while (reader.Read() && cont < 4)//processa o ficheiro RSS

{

if (reader.Name =="item" && reader.NodeType ==XmlNodeType.Element)

{

sb.Append(

"<img src=\"images/bullet.gif\"> ");

}

if (reader.Name =="title")

{

title = reader.ReadString();

}

if (reader.Name =="link")

{

link = reader.ReadString();

}

if (reader.Name =="item" && reader.NodeType ==XmlNodeType.EndElement)

{

sb.Append(title);

sb.Append(

"<br />");

cont++;

}

}

sb.Append(

"<small>(act. " +DateTime.Now.Hour +":" +DateTime.Now.Minute +")");

}

return sb.ToString();

}

}

}

----------------------------------------

As you said, maybe the code is not in right place, but I don't know another option.

Sorry for the length of the post and thank you again for your help.

Regards,

Paulo Alves.


The Javascript error is:

Microsoft JScript runtime error: 'iDomus' is undefined

In Fiddler the error is:

An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

System.Web.HttpMethodNotAllowedHandler.ProcessRequest(HttpContext context) +103
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +317
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +65

I think the error is on the Atlas.js, but I can't figure it out.

Paulo Alves.


hello.

well, it looks like a permissions problem..are you running in medium trust?


Luis Abreu:

hello.

well, it looks like a permissions problem..are you running in medium trust?

I try even put in low trust, but the error is the same.

In my web.config I have the typical settings for Atlas:

<

sectionname="webServices"type="Microsoft.Web.Configuration.WebServicesSection"requirePermission="false"/>

<

sectionname="authenticationService"type="Microsoft.Web.Configuration.AuthenticationServiceSection"requirePermission="false"/>

<

sectionname="profileService"type="Microsoft.Web.Configuration.ProfileServiceSection"requirePermission="false"/>

<

httpHandlers>

<

removeverb="*"path="*.asmx"/>

<

addverb="*"path="*.asmx"type="Microsoft.Web.Services.ScriptHandlerFactory"validate="false"/>

<

locationpath="ScriptServices">

<

system.web>

<

authorization>

<

allowusers="*" />

</

authorization>

</

system.web>

</

location>

Thank you..

Paulo Alves.


Hello again!

I follow All the options addressed by Meisinger and Luis Abreu and with the change in the loaction of Javacript, I put it in the Head of the document, and using the Javascript Function:

timerRss1 = setTimeout("parser()", 1000);

Now it works without problems.

Thank you very mutch Meisinger and Luis Abreu for your tips.

Regards,

Paulo Alves.


hello again...

are you saying that putting the script block in the header solves the problem?


I thought the position of the script has influence, but I put it back in the body and still working. The change that solve me part of the problem was in the SCRIPTMANAGER:

<atlas:ServiceReferencePath="RSS.asmx"/>

When in the last version I put "Rss.asmx/js", like in examples of Atlas Team.

I make this change several times but did't work. I don't know why but now is working. A lot of people had experience some problems with atlas in some specific script blocks, maybe this has the same problem and by magic disappeared.

Regards,

Paulo Alves.


hello again.

ah, i've missed it...

well, you put the /js if you add the file by hand. for example, you could do this:

<script type="text/javascript" src="http://pics.10026.com/?src=rss.asmx/js">
</script>

when you use the scriptmanager, you can't add the /js since it'll add it automatically...

Calling a static page method using Asp.net AJAX and then clicking elsewhere on the page

Hi All! I seem to have reached a snag and hoping someone out there can help me...Basically, I am letting the user click a button on my site which uses AJAX to call a static page method on my page which runs a complicated query in my database. The query can take up to 5 minutes to complete so I wanted to use AJAX to let the user still surf my site while the query was running in the background. However, once the user clicks on a button and tries to navigate anywhere else on the site the browser gets "stuck". It won't let you surf anywhere else...it sort of just hangs there until the browser receives a message back form the server saying the query succeeded or failed. I thought you can make more than one web service call at once? If you can't, is there a way to make a call to the server, but not necessarily wait back for a response?

Any help would be appreciated. Thanks!

The Ajax webservice/pagemethod call is always async, you should be able to do the other operations in the page. Can you pls post your code, so that we can verify it.


Below is my aspx code:

<scriptlanguage="javascript"type="text/javascript">

// <!CDATA[

function Button1_onclick() {

PageMethods.WriteReport(OnSucceeded);

}

function OnSucceeded(result)

{

$get('GenerateLabel').innerHTML = result;

}

// ]]>

</script>

</head>

<bodystyle="text-align: center">

<formid="form1"runat="server">

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="True"/>

<inputid="Button1"style="position: relative"type="button"value="Run Report"onclick="Button1_onclick()"/>

This is my code behind page:

[WebMethod]publicstaticString WriteReport()

{

String UserName =HttpContext.Current.User.Identity.Name;

int reportsID = (int)HttpContext.Current.Session["reportsID"];

Reports rep = (Reports)HttpContext.Current.Session["Report"];

try

{

Sharing.WriteActualReport(reportsID, rep, UserName); //This is the method that takes a few minutes to complete and where it get stuck.

}

catch (Exception)

{

return"An error occurred."

}

return"Success!";

}


There is nothing wrong in your code. You should be able to do any thing when the method is in progress. but what other operations you are trying to do?


KaziManzurRashidsuggested the following solution which worked on my computer. I'm still not sure why calling a static page method still stalls my site (on my computer), but the below code seemed to work well:

KaziManzurRashid:

No i did not encounter that, I was able to click different parts of the page. [Edited] It is not a good practise to run such a long process in the server. However, you can utilize the ThreadPool to generate this report in the server. in that case the the message will be returnded instantly to the user. May be the following will code will help you:

[WebMethod()]public string GenerateReport(string param1,string param2){ System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GenerateReportInternal),new object[] { param1, param2 });return"Report generation started";}private void GenerateReportInternal(object state){object[] pair = (object[])state;string param1 = (string)pair[0];string param2 = (string)pair[1];//Generate your Report over here. //Fake delay for your test. System.Threading.Thread.Sleep(1000 * 60 * 5);}

Thanks again!

Calling a simple JS Function in the "Atlas way"

How could I, from an server-side control (like a Button), call an JS Function?
In the "old way", I used theRegisterClientSideScriptBlock to do this, but it does not work in the Atlas.

Thanks in Advance for the attention,
Fract4L

RegisterClientSideScriptBlock isn't working anymore for you with Atlas? Could you post a code sample showing the problem and describe what error you're getting if any?


I haven't tested this with Atlas but I assume it should work. This might even be some deprecated method of calling a JS funcion from a .NET control but I would always add the following to the page_load.

Button1.Attributes.Add("OnClick", "HelloWorld();")

Not sure again if this will work in Atlas, but it does add the js event function to the button itself.

JoeWeb


hello.

use the overload that has a boolean as its last parameter. this method will generate the correct script block in all cases (i think that you're script string has <script type='javascriopt'> on it, right? if you fo this, it won't work in atlas because only the scripts that have the type attribute set to text/javascript will be correctly loaded by the platform).

regarding the bt click handling on the client side, you can also use the new onclientclick property intesad of using the attributes collection.


Hello all,

TheRegisterClientScriptBlock was deprecated in favor of the classClientScript, that has all the funcionallities of the old method and some new ones.


Either way, thanks in advance for your fast responses and I hope that this question could help others.

Fract4L

Here is the code:

1protected void btnAccess_Click(object sender, EventArgs e)2{3// this works fine ;-)4StringBuilder sb =new StringBuilder();5sb.Append("<script type=\"text/javascript\">");6sb.Append("alert('test');");7sb.Append("</" +"script>");8ClientScript.RegisterClientScriptBlock(this.GetType(),"test", sb.ToString());9}

hello.

i'd remove the lines <script> and </script> and add ,true to the registerclientscriptblock method.

Monday, March 26, 2012

calling a javascript function in tabpanels button

Hi

I want to call a javascript function on a button_click() event. I was able to call this function without using tabcontrol. but I want to call this function by clicking on a button which is inside a tabpanel control .

Thanks in Advance

It should work, what is you code?

Can you provide a repro?


I have two tab panels , first one showinggoogle map .

<cc1:TabPanel ID="tab_google" runat="server">

<HeaderTemplate>Google Map</HeaderTemplate>
<ContentTemplate>
<div id="map" style="width:617;height:400" >

</div>
<input type="hidden" id="go" runat="server"/>
</ContentTemplate>
</cc1:TabPanel>

Its woking properly

and second tab panel having two <select> control.

See Below for Code

<cc1:TabPanel id="tab_distancecalc" runat="server" >
<HeaderTemplate>Distance Calculator</HeaderTemplate>
<ContentTemplate>
<div id="distance_calc" >
<form name=xyz>
<table cellspacing=0 cellpadding=0 align=center border=0>
<tbody>
<tr>
<td><font face=Verdana color=#800000 size=-1><b>Originating Point :</b></font></td>
<td align=left><b><font face=Verdana color=#800000 size=-1>Terminal Point :</font></b></td>
</tr>
<tr>
<td align="center">
<select size=12 name=abc>
<option
value=/1/0.158995591/-1/1.369611552 selected>Abiramam ,TN</option>
<option value=/1/0.526186067/-1/1.295638007>Abohar ,Punjab</option>
<option value=/1/0.371031746/-1/1.353291005>Achalpur ,Maharashtra</option>
<option
value=/1/0.275936067/-1/1.396306437>Addanki ,AP</option
<option
value=/1/0.343536596/-1/1.371362434>Adilabad ,AP</option>

</select>
</td>

<td align=middle>
<select size=12 name=pqr>
<option
value=/1/0.158995591/-1/1.369611552 selected>Abiramam ,TN</option
<option value=/1/0.526186067/-1/1.295638007>Abohar ,Punjab</option>
<option value=/1/0.371031746/-1/1.353291005>Achalpur ,Maharashtra</option>
<option
value=/1/0.275936067/-1/1.396306437>Addanki ,AP</option>
<option
value=/1/0.343536596/-1/1.371362434>Adilabad ,AP</option>
<option
value=/1/0.27280291/-1/1.349202381>Adoni ,AP</option>
<option
value=/1/0.410181658/-1/1.502780423>Adra ,WB</option>
</select>
</td>
</tr>
</tbody>
</table>
<p align="center">
<input onClick=DoCalc() type=button value=" Measure " name="button"></p>
<asp:Button ID="btn_mesure" runat="server" Text="Mesure" OnClientClick="DoCalc() return false" CausesValidation="False" ValidationGroup="distance_calc" />
</form>
</div>

</ContentTemplate>
</cc1:TabPanel>

Here is Java Script (This Java Script function should display distance )

<script language=JavaScript>
<!-- Begin
var eind=new Array();
var tourism=new Array();
var a=0;
var b=0;
function DoCalc() {
if (xyz.abc.options[xyz.abc.selectedIndex].value == null || xyz.pqr.options[xyz.pqr.selectedIndex].value==null) {
alert("Please enter both an Originating and a terminal place.");
}
else {
eind=xyz.abc.options[xyz.abc.selectedIndex].value.split("/");
tourism=xyz.pqr.options[xyz.pqr.selectedIndex].value.split("/");
d=Math.acos(Math.sin(eind[2])
*Math.sin(tourism[2])
+Math.cos(eind[2])
*Math.cos(tourism[2])
*Math.cos(eind[4]-tourism[4]));
a=Math.round(3956.073*d);
if (Math.sin(tourism[4]-eind[4]) < 0) {
b=Math.acos((Math.sin(tourism[2])
-Math.sin(eind[2])*Math.cos(d))
/(Math.sin(d)*Math.cos(eind[2])));
}
else {
b=2*Math.PI
-Math.acos((Math.sin(tourism[2])
-Math.sin(eind[2])
*Math.cos(d))/(Math.sin(d)
*Math.cos(eind[2])));
}
b=b*(180/Math.PI);
alert("Distance measured is:" +" " + Math.round(a*1.6094) +" "+ "kms.");
alert("hi");
}
}
// End -->
</script>


It has nothing to do with the tab panel. Calling a javascript function is the same no matter how many layers of control nesting there are. The problem is that you are missing a semicolon between "DoCalc()" and "return false". Use:

OnClientClick="DoCalc(); return false"
or
OnClientClick="DoCalc(); return false;"


I am geeting java script error "xyz is undefined"

xyz is a form which is declared inside tabpanel.


Hi,

May you try document.getElementById("xyz"), If xyz is runat server,use document.getElementById("<%=xyz.clientID%>").

Best Regards,

Call Server Side Function before showing Modal Popup

I m showing Modal Popup on click of Edit Link Button of Datagrid.

Now when Link button is clicked I want to show the values of that particular row in Modal Popup.

This has to be done at server side as it would be updation of row and it has dropdown which has to be filled at server side..

So plz help ..

Below i m attaching the code:

<%@dotnet.itags.org.PageLanguage="VB"AutoEventWireup="false"CodeFile="ModalPopUp_In_Datagrid.aspx.vb"Inherits="ModalPopUp_In_Datagrid" %>

<%@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

<scripttype="text/javascript"language="javascript">

function shopModalPopup(employeeID){

//show the ModalPopupExtender

$get("<%=Label1.ClientID %>").value = employeeID;returnfalse;

}

</script>

<styletype="text/css">

.modalBackground

{

background-color:#000;

-moz-opacity:0.7;

opacity:.70;filter:alpha(opacity=70);

}

</style>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:ScriptManagerID="ScriptManager1"runat="server">

</asp:ScriptManager>

</div>

<asp:PanelID="Panel1"runat="server"Height="50px"Width="125px">

<asp:GridViewID="GV1"runat="server"AutoGenerateColumns="False"DataKeyNames="RID">

<Columns>

<asp:BoundFieldDataField="rid"HeaderText="rid"/>

<asp:BoundFieldDataField="name"HeaderText="Name"/>

<asp:TemplateField>

<ItemTemplate>


<cc1:ModalPopupExtender ID="ModalPopupExtender2" runat="server" PopupControlID="popupPanel"
OkControlID="btnOk" CancelControlID="btnCancel" BackgroundCssClass="modalBackground" TargetControlID="lnkPopup">
</cc1:ModalPopupExtender>

<asp:LinkButtonrunat="server"Text="Popup"CommandName="EditRow"CausesValidation="false"ID="lnkPopup"OnCommand="lnkPopup_Command"></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</asp:Panel>

<asp:PanelID="popupPanel"runat="server"Height="50px"Width="125px">

Click To Display Authors Name:

<asp:LabelID="Label1"runat="server"></asp:Label>

<br/>

<br/>

<asp:ButtonID="btnOk"runat="server"Text="OK"/>

<asp:ButtonID="btnCancel"runat="server"Text="Cancel"/>

</asp:Panel>

<br/>

</form>

</body>

</html>

Hi Varun,

Please don't attach a hidden Control(visible= false) to your ModalPopupExtender or it won't work because no Dom element generate to the client. Also don't put $get function before ScriptManager. Here is the sample , please pay attention to the "Bold" part.

<%@. Page Language="VB" %><%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> Sub fill_values() Label1.Text = "a" End Sub Protected Sub GV1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) If e.CommandName = "EditRow" Then fill_values() ModalPopupExtender2.Show() End If End Sub</script><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"> <title>Untitled Page</title> <style type="text/css"> .modalBackground { background-color:Gray; filter:alpha(opacity=70); opacity:0.7; } .modalPopup { background-color:#FFD9D5; border-width:3px; border-style:solid; border-color:Gray; padding:3px; width:250px; } </style></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Panel ID="Panel1" runat="server" Height="50px" Width="125px"> <asp:GridView ID="GV1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" AllowPaging="True" onrowcommand="GV1_RowCommand" > <Columns> <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" /> <asp:BoundField DataField="LastName" HeaderText="LastName" /> <asp:BoundField DataField="FirstName" HeaderText="FirstName" /> <asp:BoundField DataField="Title" HeaderText="Title" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton runat="server" Text="Popup" CommandName="EditRow" CausesValidation="false" ID="lnkPopup"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString%>" SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees]"></asp:SqlDataSource> </asp:Panel> <asp:Panel ID="popupPanel" runat="server" CssClass="modalPopup" Height="200px" Width="200px" style="display:none"> Click To Display Authors Name: <asp:Label ID="Label1" runat="server"></asp:Label> <asp:Button ID="btnShowAuthorName" runat="server" Text="Show Author's Name" OnClientClick="getName(); return false;"></asp:Button><br /> <asp:Label ID="lblAuthorsName" runat="server" BackColor="Beige" ForeColor="Red"></asp:Label> <br /> <br /> <asp:Button ID="btnOk" runat="server" Text="OK" /> <asp:Button ID="btnCancel" runat="server" Text="Cancel" /> </asp:Panel><cc1:ModalPopupExtender ID="ModalPopupExtender2" runat="server" PopupControlID="popupPanel" BackgroundCssClass="modalBackground" TargetControlID="Label2" CancelControlID="btnCancel" OkControlID="btnOk"> </cc1:ModalPopupExtender> <div style="display:none"> <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div> <script type="text/javascript" language="javascript">function getName(){ var labelValue = $get("<%=Label1.ClientID%>").innerHTML; } </script> </form></body></html>

Best regards,

Jonathan


Hi Varun,

Here is another sample which won't postback when click to show the ModalPopupExtender.

<%@. Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server"
protected void Page_Load(object sender, EventArgs e)
{
//Attach a Javascript funtion to the LinkButton.
LinkButton myLinkButton;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
myLinkButton = (LinkButton)GridView1.Rows[i].Cells[4].FindControl("LinkButton1");
myLinkButton.Attributes.Add("onclick", "shopModalPopup('" + GridView1.Rows[i].Cells[0].Text + "');return false;");
}
}
</script
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style>
.modalBackground {
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}

.modalPopup {
background-color:#FFD9D5;
border-width:3px;
border-style:solid;
border-color:Gray;
padding:3px;
width:250px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"
ReadOnly="True" SortExpression="EmployeeID" ItemStyle-Width="0" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Click On Me</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString%>"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees]">
</asp:SqlDataSource>
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" Height="200px" Width="300px" style="display:none">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
EmployeeID:<asp:TextBox ID="tbEmployeeID" runat="server"></asp:TextBox> <br/>
Reason:<asp:TextBox ID="tbReason" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</asp:Panel>
<div style="display: none">
<asp:Button ID="Button1" runat="server" Text="Button" /></div>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button1"
PopupControlID="Panel1" CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<script type="text/javascript" language="javascript">
function shopModalPopup(employeeID){
//show the ModalPopupExtender
$get("<%=tbEmployeeID.ClientID%>").value = employeeID;
$get("<%=tbReason.ClientID%>").value ="";
$find("<%=ModalPopupExtender1.ClientID%>").show();
}
</script>
</form>
</body>
</html>

Best regards,

Jonathan

Call RegisterStartupScript problem

Dear friends,

I'm having problems to execute a RegisterStartupScript when I click on a button.
For example:

protected void btnSave_Click(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "OnLoad", "<script language='javascript'>alert('OK');</script>" );
}

If I disable the Atlas tags, the RegisterStartupScript works OK, but if I enable the Atlas tags, It doens't work.

How I correct this?

Try setting addScript Tags = True instead

Page.ClientScript.RegisterStartupScript(typeof(Page), "OnLoad", "alert('OK');", True);

RG


I put the True in the last parameter but not works.
Remember thar I'm using Atlas ok.

Do you havy any other sugestion?


just putting the following line in a button even which is inside the update panel works fine for me

Page.ClientScript.RegisterStartupScript(typeof(Page),"OnLoad","alert('OK');",true);

there must be some other issues in the page, you have to show the code.

Thanx


Not work again.

All my controls are inside the same updatepanel, for example:
...
<body>
<form .....>
<atlas:updatepanel .....>
//Here all tags and all controls
</atlas>
</form>
</body>

Is It a problem?


well you have to paste the whole non working code, without the code its hard to tell...


use following code

protected void btnSave_Click(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "OnLoad", "alert('OK');",true );
}

I think u'r code remain having "<script language='javascript'>alert('OK');</script>" . This is the problem. U shouldn't use "<script" tag if last parametere is 'true'


I have found that I must have the semi-colon after the script. EG:


page.ClientScript.RegisterClientScriptBlock(typeof(Page), "ShowMsg", "alert('hi')", true);


doesn't work BUT


page.ClientScript.RegisterClientScriptBlock(typeof(Page), "ShowMsg", "alert('hi');", true);

does!


is there a solution? I have the same porblem like rasl


http://ajax.asp.net/docs/mref/T_System_Web_UI_ScriptManager.aspx

You can use the scriptmanager.

Dim msgAsString ="Group '" & u.GroupCode &"' has been deleted."
ScriptManager.RegisterStartupScript(Me.Page,GetType(String),"alertdelete","reportMessage('" & Utils.ForJavascript(msg) &"');",True)

Saturday, March 24, 2012

Calenderextender problem

when I use the CalenderExtender with a html button as popupbutton and a asp.net text field as target control it works fine. but the problem is when the calender becomes visible if there are any dropdownlist then it is on the calender. so part of the calender becomes invisible. i.e. goes behind the DropDownList.

but if there is a textbox in the position of the DropDownList then everything works fine.

how do i solve this issue? Any idea?

Hi

I'm afraid that it's a normal thing and no solution yet,just avoid it.

Best regards

Calender control in asp.net

Hi, Could anyone please tell me how can i display datepicker when i click textbox or button and i want the date to be in textbox.

could any one give me code to do thhis? i have master page in my project

Thanks for any assistance

Have a look at the ASP.NETAJAX Calendar control.


Hi Tweety,

If you want use CalendarExtender, please download theAjax Control Toolkit. And some pretty samples are contained inside the package.

I hope this help.

Best regards,

Jonathan


Hi. thanks for both of you

im using ajax calender tool kit, jus searchin for good design(i mean css) to apply.

if u have any please suggest me.

thanks again


It really depends on your application as to what style to apply, but if you read thecalender page (specifically the theming section) it will show you how you can customize it to suit your application.


<asp:TextBoxID="TextBox5"runat="server"Width="120px"CssClass="textile"></asp:TextBox></td>

<cc1:CalendarExtenderrunat=serverTargetControlID=textbox5Format="dd/MM/yyyy">

</cc1:CalendarExtender>

im using this code.i have a pblm here once i selected date my date appears in textbox but the calender still can able to see until i clik some where on the page...

why like this?


That's how the control has been built. View thecalendar page for 3 different examples on how it behaves.


Hi Tweety,

If you want to hide the Calendar immediately after we selected a date, you should add thisOnClientDateSelectionChanged="function hideCalendar(cb) { cb.hide(); }" to your source code. OnClientDateSelectionChanged is one property of the CalendarExtendar.

Hope this helps.

Best regards,

Jonathan


Hi thanks but once a date is selected calender hide , but when i reclick the textbox it wont appears...

did i need to quote another javascript here to make calender visible when i click textbox after date selection?


Its fixed...thanks.

http://forums.asp.net/t/1067091.aspx?PageIndex=2

i found my soluntion here..

thanks for everyone.

forums.asp.net ROCKS!!!!

Wednesday, March 21, 2012

CalendarExtender question

I have a textbox, an image button and a calendar extender on my form. If I go with the default and don't make an entry for the PopupControlID attribute, the calendar gets displayed when the textbox gets focus and I can select a date from it. If I use the image button as the entry for the PopupControlID attribute, the calendar initially gets displayed but then the whole page posts to the server and returns before a date can be selected. There aren't any AJAX controls on the MasterPage and nothing in it's code-behind that would cause this issue. There also isn't currently any code-behind in my form ... just HTML ... and I'm posting it in its entirety below:

<%@dotnet.itags.org.PageLanguage="VB"MasterPageFile="~/MasterPages/MasterPage.master"AutoEventWireup="false"CodeFile="CalendarTest.aspx.vb"Inherits="Correspondence_CalendarTest"title="Untitled Page" %>
<%@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>

<asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"Runat="Server">

<asp:ScriptManagerrunat="server"></asp:ScriptManager>
<br/><br/>
<asp:TextBoxID="Date1"runat="server"></asp:TextBox>
<asp:ImageButtonID="ImageButton1"runat="server"ImageUrl="~/Images/Calendar_scheduleHS.png"/>
<cc1:CalendarExtenderID="CalendarExtender1"runat="server"TargetControlID="Date1"PopupButtonID="ImageButton1">
<%--
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="Date1">
--%>
</cc1:CalendarExtender>

</asp:Content>

Why does this bloody thing insist on posting back to the server and is there anything I can do to prevent it from occurring?

TIA,

Allen

this is from another issue close to what you have because when you click the button a second time it does a post back as well. there is the solution from another post.

just to say, I've found this can be solved by creating a plain html img tag and assigning the popubbutton id to that instead of an asp imagebutton control


Did you make sure the CAUSESVALIDATION property of the Calendarextender is set to false? There is no problem using an asp:imagebutton control if you have that done. I mean that way when the Calendar control is clicked, all that happens is the control opens and selection is made.

Dollarjunkie