Showing posts with label user. Show all posts
Showing posts with label user. Show all posts

Wednesday, March 28, 2012

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 javascript from a js file

I have a js file that contains the function that i want called when the user clicks on the textbox and the calendarextender is shown

calendarextender.onShown = functionName

Working with a single page i have put this at the top inside the head

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

With a single page is works perfectly but now i want to make it add this to a master page

creating a masterpage i have also added the same line inside the head, but when i try and run my content page and click on the textbox i get "Error: object is required"

I have viewed the source and made sure that the <script> line is present. Also have tried pasting the function directly on the master page instead of pointing to a file

<script type= "text/javascript" >

function dosomething() </script>

and i get the same error

anybody got a suggestion on how i can get my master/content page to work with my js file

Thanks

allan

I could be wrong, but I don't think the <head /> element from the Master Page is included when the page is sent to the browser - you normally set the info in the content page as you'd expect things like the title and meta tags to be different.

You can do a quick "view - source" on the executed page to check this and if it's the case, you could included the script tag right at the top of your <body /> element - as long as it appears before the call to the function.

calling external javascript functions/ library from within an update panel

I have an application with a large number of javaScript functions that reside in external .js files. User controls that reference these files work perfectly.

When usercontrols inside updatepanels call the external javascript functions and libraries, they fail with 'object not found' errors.

I tested using the scriptmanager.registerclientscriptblock by adding a concatenated string with a simple function and it worked. But this is a bad way to do things both from a debugging standpoint as well as ease of code. There must be a better way?

Dim scriptTextAsString

scriptText = _

"function prepareToClose() {"

& _

"alert('prepare to close');"

& _

"test();"

& _

" }"

System.Web.UI.ScriptManager.RegisterClientScriptBlock(

Me.btnLoad,Me.GetType(),"prepare_close", scriptTextTrue)

btnLoad.Attributes.Add(

"onCLick","prepareToClose(); return false;")

What is the best way to do this?

Unless someone has a better solution, here is what I did. Basically, I load the external file into a string and use the rgisterScriptBlock...everything works well and there is still just 1 instance of the scripts for easy maintenance and other non-ajax pages can use them. Here is the code for anyone interested.:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.btnClose, Me.GetType(), "objectives", regLongScript("objectives.js"), True)


...

Private Function regLongScript(ByVal incoming_name As String) As String
Dim objStreamReader As IO.StreamReader
Try
Dim file_name As String = ""
file_name = Request.PhysicalApplicationPath & "a\js_scripts\" & incoming_name
objStreamReader = File.OpenText(file_name)
Return objStreamReader.ReadToEnd()

Catch ex As Exception
Return ""
Finally
objStreamReader.Close()
End Try
End Function


Here's how I've been doing it:

ScriptManager.RegisterStartupScript(

UpdatePanelTest,

UpdatePanelTest.GetType(),

"keyValue",

"alert('test')",

true);


Here's how I've been doing it:

ScriptManager.RegisterStartupScript(

UpdatePanelTest,

UpdatePanelTest.GetType(),

"keyValue",

"alert('test');",

true);

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 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!

Saturday, March 24, 2012

CalendarExtender: Anyway to AutoPostBack?

I'd like to cause a post back when a user selects a date using the CalendarExtender. Anyway to do this?

You could try this...

1) Add the following code to your page's OnLoad event - this basically registers a function to handle the calendar date selection change on the client and force a postback (sorry if you're a C# person)

Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.LoadConst strKeyAs String ="calendarExtenderPostback"If Not Me.ClientScript.IsClientScriptBlockRegistered(Me.GetType(), strKey)Then Dim pboAs PostBackOptions =New PostBackOptions(Me) pbo.AutoPostBack =True pbo.RequiresJavaScriptProtocol =False pbo.PerformValidation =True Dim strScriptAs String =String.Format("function calendarExtenderPostback(e) {{ {0} }}",Me.ClientScript.GetPostBackEventReference(pbo).ToString)Me.ClientScript.RegisterClientScriptBlock(Me.GetType(), strKey, strScript,True)End If End Sub

2) Add the following markup to your page to create the script manager, textbox and calendar extender... NB the use of OnClientDateSelectionChanged

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

<asp:TextBoxID="DateTextBox"runat="server"/>

<ajaxToolkit:CalendarExtenderID="CalendarExtender1"runat="server"TargetControlID="DateTextBox"Format="dd MMM yyyy"OnClientDateSelectionChanged="calendarExtenderPostback"/>


This works...to a point. It causes a postback, but not one that UpdatePanels seem to recognize. When I cause a postback using a button the content on my page in updatepanel's correctly updates. When I use the CalendarExtender autopostback method you described, the whole page refreshes. Any ideas?


There are quite a few posts on these forums for forcing an UpdatePanel to postback... it doesn't look like there currently a "correct" method of doing this (e.g. UpdatePanel.Update()) - though I might be wrong...

Suggestions include having a hidden button (using style="display: none") in your UpdatePanel which triggers the update.

You can then force the Click event for this in the code I described above (instead of the postback code)... which will in turn force the UpdatePanel to update!

This post may help...http://forums.asp.net/thread/1426873.aspx

Hope this makes sense!

Wednesday, March 21, 2012

CalendarExtender, want only current month date visible

hi all,

I have a problem, I want to display days of only current month or whichever month a user selects. I mean by default calendar extender shows all dates , even if we have selected November, it will show some days of previous month and some days of next month along with current month's dates. I only want to display current month's dates.

I applied css specified in http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx

but that's changing color of each day. I was thinking by using css somehow i will hide previous and next month days, but of not avail.

please suggest,

thanks...

Hi Forums_user,

As far as I know, it is not supported now unless you modify its source code. CalendarExtender generate all the days , months and years on the client, you can find it in its source code with the name _buildDays,_buildMonths and _buildYears.

I hope this help

Best regards,

Jonathan

CalendarExtender, MaskedEditExtender, and MaskedEditValidator

Hi all,

I have this fiddly situation where I have a MaskedEditExtender to give me a date mask on a TextBox, and a MaskedEditValidator to give the user feedback if the date is invalid - empty is allowed. I also have a CalendarExtender on this TextBox so the user doesn't have to type. I have two things to note:

    When you set "ClearMaskOnLostFocus" of the extended TextBox properties, the CalendarExtender doesn't work - you can set the date, but when you click away to hide the calendar, it also resets the mask and the TextBox content.When you do not have "ClearMaskOnFocus" set, allow empty values, click in the TextBox (to bring up the input mask), and click out again - the input mask remains and any validation message you attached to the MaskedEditValidator now appears - this goes against what I expect to be correct, as the TextBox is empty.

The third problem that I won't number is that the two problems are exacerbated by the CalendarExtender, without that only the second problem would persist, which could furthermore be solved by setting "ClearMaskOnLostFocus". I haven't tested what happens to the TextBox and its values etc in any other situation.

Has anyone else encountered this issue?

Temporarily, does anyone have a work around? I require the calendar object to give the user a mouse option, and need a basic input mask toat leastblock out alphabetic characters and format the date in dd/MM/yyyy format.

Thanks in advance!

Hello. Might be a bit late for an reply, but I had the same problem as you. I was using a textBox with a MaskedEdit & a CalendarExtender.

I was clicking on the textbox, the calendar was showing up. One time on two, it was telling me the date was invalid (but it was valid). And the weirdest thing was when I clicked on a date, it was writing it in the textbox, saying it was valid. But as soon as I clicked outside the calendar to close it, the validator was emptying the textbox and telling me it was an invalid date.

I was losing it, but strangely, when I read your post I decided to try adding a "ClearMaskOnLostFocus="False" (that parameter wasn't originally declared so I don't know what is the default value). and now ... it WORKS 100%.

Btw, I'm using DD/MM/YYYY format. The easiest trick to do that is simply to set the MaskedEditExtender's culture to "en-GB" and it worked #1. Here's my code of a working textbox with a calendar, all using the DD/MM/YYYY format.

<asp:LabelID="Label5"runat="server"Font-Bold="True"Font-Size="Smaller"Style="text-align: right"

Text="DATE DéPART:"Width="143px"></asp:Label>

<asp:TextBoxValidationGroup="dateValidator1"MaxLength="1"ID="dateDepart"runat="server"style="text-align:center"Width="77px"></asp:TextBox>

<asp:LabelID="Label14"runat="server"Width="68px"></asp:Label>

<cc1:MaskedEditValidatorID="MaskedEditValidator1"runat="server"

ControlExtender="MaskedEditExtender1"

SetFocusOnError="true"

Display="Dynamic"

ControlToValidate="dateDepart"

IsValidEmpty="False"

EmptyValueMessage="Date is required"

InvalidValueMessage="Date is invalid"

ValidationGroup="dateValidator1"

TooltipMessage="Input a Date"/>

<asp:LabelID="Label7"runat="server"Width="75px"></asp:Label><br/>

<cc1:CalendarExtenderID="CalendarExtender1"runat="server"Format="dd/MM/yyyy"TargetControlID="dateDepart">

</cc1:CalendarExtender>

<br/>

<br/>

<cc1:MaskedEditExtenderID="MaskedEditExtender1"runat="server"

MaskType="Date"

TargetControlID="dateDepart"

Mask="99/99/9999"

CultureName="en-GB"

MessageValidatorTip="true"

OnFocusCssClass="MaskedEditFocus"

OnInvalidCssClass="MaskedEditError"

ClearMaskOnLostFocus="false"

DisplayMoney="Left"

AcceptNegative="Left"/>

<br/>

Pat.


I ran into some of the same problems. My issue was allowing for empty values w/out invalidating. Seethis post for more info and sample code.

Hope this helps.

CalendarExtender, MaskedEditExtender, and MaskedEditValidator

Hi all,

I have this fiddly situation where I have a MaskedEditExtender to give me a date mask on a TextBox, and a MaskedEditValidator to give the user feedback if the date is invalid - empty is allowed. I also have a CalendarExtender on this TextBox so the user doesn't have to type. I have two things to note:

    When you set "ClearMaskOnLostFocus" of the extended TextBox properties, the CalendarExtender doesn't work - you can set the date, but when you click away to hide the calendar, it also resets the mask and the TextBox content.When you do not have "ClearMaskOnFocus" set, allow empty values, click in the TextBox (to bring up the input mask), and click out again - the input mask remains and any validation message you attached to the MaskedEditValidator now appears - this goes against what I expect to be correct, as the TextBox is empty.

The third problem that I won't number is that the two problems are exacerbated by the CalendarExtender, without that only the second problem would persist, which could furthermore be solved by setting "ClearMaskOnLostFocus". I haven't tested what happens to the TextBox and its values etc in any other situation.

Has anyone else encountered this issue?

Temporarily, does anyone have a work around? I require the calendar object to give the user a mouse option, and need a basic input mask toat leastblock out alphabetic characters and format the date in dd/MM/yyyy format.

Thanks in advance!

Apologies, I appear to have double posted - use the other one :)

CalendarExtender Question

I was wonering if there is a way to fire a javaScript function after the user selects a date. Kind of like in the ModelPopup where we can set the onOkScript property except this would be like an OnDateChangedScript property...is there an easy way to do this with the CalendarExtender? Basically the date would already be updated on the screen and I want to call this javaScript function to send the new date back to the data base via JavaScript/WebService...Any thoughts?

Thanks, Greg

That is what the onClientDateSelectionChanged method is for!!...nevermind.

I have an example as to how to fire a javaScript event after the user select a different date...you can see the code here:http://forums.asp.net/thread/1627224.aspx