Solved

execute code behind before javascript function

Posted on 2011-09-23
4
821 Views
Last Modified: 2012-05-12

I have a button within a listview that I set an onclick attribute to execute a javascript function.  This button also has a command argument that executes in code behind.
Both work, but it currently executes the javascript before the code behind. I need to execute the code behind before the javascript.
How would I do this?
Thankis

### button in listview

<span onclick="return confirm('Create/Edit Service from this Schedule?')">
<asp:Button ID="LnkCreateService" runat="server" CommandArgument='<%# Eval("ServicesLU.LUServiceID")%>'           CommandName="CreateService" ForeColor="Navy" Text="Create/Edit Service" />
</span>

### attribute added during itemdatabound

   Protected Sub lstSchedules_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs)
      Dim Schedule As Label
      Dim isComplete As HiddenField
      Dim img As Image
      If e.Item.ItemType = ListViewItemType.DataItem Then
         ' Display the e-mail address in italics.
         Dim buttCreate As Button = DirectCast(e.Item.FindControl("LnkCreateService"), Button)
         If Not buttCreate Is Nothing Then
            buttCreate.Attributes.Add("onclick", "javascript:clickcreateschedule(1)")
         End If
         Schedule = DirectCast(e.Item.FindControl("lblSched"), Label)
         isComplete = DirectCast(e.Item.FindControl("isComplete"), HiddenField)
         img = DirectCast(e.Item.FindControl("img"), Image)
         If isComplete.Value = "True" Then
            img.Visible = True
            ' Schedule.Text = Server.HtmlDecode(Schedule.Text + "<img src ='~/images2020/checkmark_32.png'  alt='Yes' />")
         Else
            img.Visible = False
         End If
      End If
   End Sub


### Code behind needs to execute first

   Protected Sub CreateService(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs)
      Dim dataItem As ListViewDataItem = CType(e.Item, ListViewDataItem)
      Dim item As ListViewItem = e.Item
      Dim u As New SalonUtilities
      If e.CommandName = "CreateService" Then 'can i add text

         ClearCompleteService()

         Dim sSchedID As String = Me.lstSchedules.DataKeys(dataItem.DisplayIndex).Value.ToString
         Dim iSchedID As Integer = u.ReturnInteger(sSchedID)
         Me.txtSchedID.Text = sSchedID
         Dim hServID As HiddenField = DirectCast(item.FindControl("HiServiceID"), HiddenField)
         Dim sServID As String = hServID.Value.ToString
         Dim iServID As Integer = u.ReturnInteger(sServID)
         Dim sLUServID As String = DirectCast(e.CommandArgument, String)
         Dim iLUServID As Integer = u.ReturnInteger(sLUServID)
         Dim hiCustID As HiddenField = DirectCast(item.FindControl("HiCustID"), HiddenField)
         Dim sClientID As String = hiCustID.Value.ToString
         Dim iClientID As Integer = u.ReturnInteger(sClientID)
         Me.HiCustomerID.Value = sClientID
         EvalServiceFromSelectedAppt(iClientID, iLUServID, iServID, iSchedID)

         Me.chkAddPicsToPortfolio.Checked = True
         '   ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "clickcreateschedule", "clickcreateschedule(1);", True)
         Dim lbl As Label = DirectCast(item.FindControl("lblClient"), Label)
         If Not lbl Is Nothing Then
            Me.lblClientName.Text = lbl.Text
         End If
         FillPictures()
         EnableDisable()
      ElseIf e.CommandName = "DeleteSched" Then
         Dim sSchedID As String = Me.lstSchedules.DataKeys(dataItem.DisplayIndex).Value.ToString
         Dim iSchedID As Integer = u.ReturnInteger(sSchedID)
         Using dc As New SalonDataClassesDataContext
            Dim sch = (From p In dc.Schedules Where p.SchedID = iSchedID Select p).FirstOrDefault
            dc.Schedules.DeleteOnSubmit(sch)
            dc.SubmitChanges()
         End Using
         FillSchedules()
      ElseIf e.CommandName = "NoShow" Then
         Dim tr As HtmlTableRow = DirectCast(item.FindControl("trNoShowDetails"), HtmlTableRow)
         ShowHideTree(tr)
      ElseIf e.CommandName = "NoShowCancel" Then
         Dim tr As HtmlTableRow = DirectCast(item.FindControl("trNoShowDetails"), HtmlTableRow)
         ShowHideTree(tr)
      ElseIf e.CommandName = "NoShowUpdate" Then
         Dim tr As HtmlTableRow = DirectCast(item.FindControl("trNoShowDetails"), HtmlTableRow)
         Dim hiCustID As HiddenField = DirectCast(item.FindControl("HiCustID"), HiddenField)
         Dim sClientID As String = hiCustID.Value.ToString
         Dim iClientID As Integer = u.ReturnInteger(sClientID)
         Dim sSchedID As String = Me.lstSchedules.DataKeys(dataItem.DisplayIndex).Value.ToString
         Dim iSchedID As Integer = u.ReturnInteger(sSchedID)

         Dim chk As CheckBox = DirectCast(item.FindControl("chkNoSched"), CheckBox)
         Dim txt As TextBox = DirectCast(item.FindControl("txtNoShowDetails"), TextBox)
         Using dc As New SalonDataClassesDataContext
            Dim noshow As New ScheduleNoShow
            noshow.CustomerID = iClientID
            noshow.SchedDate = Convert.ToDateTime(Me.txtCalendar.Text)
            noshow.NoShowDetails = txt.Text


            dc.ScheduleNoShows.InsertOnSubmit(noshow)

            dc.SubmitChanges()

            If chk.Checked Then
               Dim q = (From p In dc.Clients Where p.CustomerID = iClientID Select p).FirstOrDefault

               q.BlockScheduling = True
               dc.SubmitChanges()

            End If
            Dim sch = (From p In dc.Schedules Where p.SchedID = iSchedID Select p).FirstOrDefault

            dc.Schedules.DeleteOnSubmit(sch)
            dc.SubmitChanges()

         End Using

         ShowHideTree(tr)
         FillSchedules()
      End If
      ' 
   End Sub

### Javascript

function clickcreateschedule(itemindex) {
      var item = "li_" + itemindex;
      var itemsched = "li_" + "0";
      var div0 = document.getElementById("div_0");
      var div1 = document.getElementById("div_1");
      div1.style.display = "block";
      div0.style.display = "none";
      updateupdatepanel(0);
      updateupdatepanel(1);
      var obj = document.getElementById(item);
      var objSched = document.getElementById(itemsched);
      objSched.style.color = '#000000';
      objSched.style.backgroundColor = '#b9d0ff';
      obj.style.color = '#FFFFFF';
      obj.style.backgroundColor = '#000000';

      return false;
   }

Open in new window

0
Comment
Question by:Sheritlw
4 Comments
 
LVL 21

Expert Comment

by:Dale Burrell
Comment Utility
You can't... well not easily... javascript executes at the browser (client) which happens before the page is posted back to the server. Code behind runs on the server, so cannot run until the page has been posted to the server and is available to run.

There are three potential solutions I can think of:

1) Change your logic to work with the javascript first (maybe easier).

2) Send the request to the server to run the code behind using Ajax and then once the result is back run the local javascript (a bit complex if you're not already using ajax, but otherwise a nice solution)

3) Post the form back, run your code behind, and then embed the javascript you wish to run back into the page and set it to run once the page load is complete (a bit messy).
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
http://weblogs.asp.net/sohailsayed/archive/2008/02/23/calling-methods-in-a-codebehind-function-pagemethods-from-client-side-using-ajax-net.aspx
http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

In this case you only use OnClientClick="callpagemethod(itemindex)" and not OnClick

in the Page_Method success function you have :

function CallSuccess(res, destCtrl)
 {
         clickcreateschedule(itemindex); // you previously save itemindex
0
 
LVL 35

Accepted Solution

by:
Miguel Oz earned 500 total points
Comment Utility
At the end of your code behind method use RegisterStartupScript:

RegisterStartupScript("Executeclickcreateschedule", "clickcreateschedule(" & itemindex &")")
where itemIndex is a tring that contains your parameter.

Check:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript.aspx
The js code will execute after you executed code-behind.
0
 

Author Closing Comment

by:Sheritlw
Comment Utility
Thank you
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now