달력

092009  이전 다음

  •  
  •  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  •  
  •  
  •  
 

출처 : http://zeemalik.wordpress.com/2007/11/27/how-to-call-client-side-javascript-function-after-an-updatepanel-asychronous-ajax-request-is-over/



How to call client-side Javascript function after an UpdatePanel asychronous (Ajax) request is over

Posted by zeemalik on November 27, 2007

If you are using AJAX then the only way i have found yet to give an alert to a user on return to the Asynchronous post back is to add an “end request” handler to the PageRequestManager.

In this way you can tell the request manager to run a javascript function on returning from a Asynchronous post back event of AJAX.

Code for doing this is :

function load()

{
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}

where “EndRequestHandler” will be the name of your javascript function you want to call.
Call the above function in Onload event of <body> tag:

<body onload=”load()”>

function EndRequestHandler()

{

          alert(”You record has been saved successfully”);

}

Now If you want to give a different message based on your logic in server side code (code behind) then you can use a server side Hidden Field:

<input id=”hdnValue” type=”hidden” runat=”server”  value=”" />

Set its value in server side code on Asychronous Post Back: 

Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateSample.Click

    If condition Then

hdnValue.value = “do this”

    Else     

hdnValue.value = “do that”

    End If 

End Sub

Now you can check the value of this Hidden Field in your Client Side EndRequestHandler function and give a different alert to user based on its value:

function EndRequestHandler()
{
     if (document.getElementById(’<%= hdnValue.ClientID %>’).value == “do this”)

     { 
          alert(”You record has been saved successfully”);
     } 
     else
     {
          alert(”There is an error”);
     }
 }

크리에이티브 커먼즈 라이선스
Creative Commons License


Posted by tornado
 

출처 : http://aspnet.4guysfromrolla.com/articles/051408-1.aspx



Introduction
Most security systems' passwords are case-sensitive. Case sensitivity nearly doubles the number of possible characters that can appear in the password, which makes it harder for nefarious users trying to break into the system. As a result, if a user logging into the system has Caps Lock turned on, they'll enter letters in the opposite case and not be able to login. Because the textboxes that collect user input typically are masked to prevent an onlooker from seeing a user's password, the user typing in her password may not realize that Caps Lock is on. To help prevent this type of user error, many login screens for desktop-based applications display some sort of warning if the user's Caps Lock is on when they start typing in their password.

Unfortunately, such functionality is rarely seen in web applications. A 4Guys reader recently asked me if there was a way to provide such feedback to a user logging into an ASP.NET website. The short answer is, Yes. It is possible to detect whether a user has Caps Lock enabled through JavaScript. Likewise, it's possible to have this client-side logic execute whenever a user starts typing in a particular textbox. With a little bit of scripting, such an interface could be devised.

After thinking about the implementation a bit, I decided to create a compiled server-side control that would emit the necessary JavaScript. This article introduces this control, WarnWhenCapsLockIsOn, and shows how it works and how to use it in an ASP.NET web page. Read on to learn more!

 
 
An Overview of the WarnWhenCapsLockIsOn Control's Functionality
The WarnWhenCapsLockIsOn control is designed to display a page developer-specified message if a user types in a specified TextBox control with Caps Lock on. The control extends the Label class so it has the same set of properties as the Label control: Text, Font, Width, CssClass, and so on. Use these properties to configure the message and the message's appearance.

In addition to the Label control's properties, the WarnWhenCapsLockIsOn control also has a TextBoxControlId property, which you must set to the ID of a TextBox control. This property is required. (To provide a Caps Lock warning for multiple TextBox controls on the page, add a WarnWhenCapsLockIsOn control for each TextBox.) If the user starts typing in the specified textbox with the Caps Lock on, the WarnWhenCapsLockIsOn control is displayed. The WarnWhenCapsLockIsOn control is hidden again when one of the following conditions apply:

  • The user types in the same textbox with Caps Lock off.
  • The WarnWhenCapsLockIsOn control has been displayed for WarningDisplayTime milliseconds. The WarningDisplayTime property defaults to a value of 2500, meaning that the control will be displayed for 2.5 seconds after the last character with Caps Lock on has been typed. You can lengthen or shorten this property value as needed. A value of 0 displays the warning until the user types in a character without Caps Lock on or after there's a postback.

To provide a warning to the user if Caps Lock is on, then, you'll add this control to the page, set its Text property (and, perhaps, other formatting properties), and indicate the TextBox to "watch" via the control's TextBoxControlId property. That's all there is to it! We'll discuss how to add the WarnWhenCapsLockIsOn control to your ASP.NET website project and look at an end-to-end example in the "Using the WarnWhenCapsLockIsOn Control in an ASP.NET Web Page" section later on in this article.

Initially Hiding the WarnWhenCapsLockIsOn Control
Whenever the ASP.NET page is loaded in the user's browser, the WarnWhenCapsLockIsOn control needs to be hidden so that it does not appear. The WarnWhenCapsLockIsOn control should only appear when the user starts typing in the specified textbox with Caps Lock on. To initially hide the WarnWhenCapsLockIsOn control, I overrided the control's AddAttributesToRender method and added code that set the visibility and display style attributes to "hidden" and "none", respectively.

public class WarnWhenCapsLockIsOn : System.Web.UI.WebControls.Label
{
   protected override void AddAttributesToRender(HtmlTextWriter writer)
   {
      base.AddAttributesToRender(writer);

      // Add a style attribute that hides this element (by default)
      writer.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden");
      writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");

   }
}

The effects of these style attribute settings are evinced by the markup sent to the browser. Because the WarnWhenCapsLockIsOn control extends the Label class, it renders as a <span> element with the value of its Text property rendered as the <span> element's inner content, just like the Label control. In the style attribute you can see that the visibility and display settings have been configured to hide the control:

<span id="ID" style="visibility:hidden;display:none;">Value of Text property</span>

We now need to write JavaScript that sets the visibility and display settings to "visible" and "inline" whenever the user types into the corresponding textbox with Caps Lock on.

Executing JavaScript in Response to Typing in a Textbox
It is possible to execute JavaScript in response to a variety of client-side events, such as when the document has loaded, when the user changes the selection of a drop-down list, when an input field receives (or loses) focus, or when the user presses a key. To execute client-side script in response to a user pressing a key, use the onkeypress event like so:

<input type="text" ... onkeypress="action" />

The action can be inline script or a call to a function. In addition to noting that a key has been pressed, JavaScript offers the event object, which includes information such as what key was pressed and whether or not the Shift key was depressed, among other useful tidbits. In short, we need to add an onkeypress client-side event handler to the TextBox control referenced by the WarnWhenCapsLockIsOn control's TextBoxControlId property. The event handler called must determine whether Caps Lock is on or off and show or hide the WarnWhenCapsLockIsOn control in response.

To add client-side event handlers to a server-side Web control use the Attributes collection like so:

WebControlID.Attributes["attribute"] = "value";

The above code adds the markup attribute="value" to the Web control's rendered output. Usually this sort of logic is applied during the PreRender stage of the page lifecycle. Therefore, to implement this functionality I overrode the OnPreRender method in the WarnWhenCapsLockIsOn class (which is fired during the PreRender stage) and added the following code:

public class WarnWhenCapsLockIsOn : System.Web.UI.WebControls.Label
{
   protected override void OnPreRender(EventArgs e)
   {
      base.OnPreRender(e);

      if (this.Enabled)
      {
         /* We need to add two bits of JavaScript to the page:
          * (1) The include file that has the JavaScript function to check if Caps Lock is on
          * (2) JavaScript that will call the appropriate function in (1) when a key is pressed in the TextBoxControlId TextBox
          */

         // (1) Register the client-side function using WebResource.axd (if needed)
         if (this.Page != null && !this.Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "skmControls2"))
            this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "skmValidators", this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "skmControls2.skmControls2.js"));


         // (2) Call skm_CountTextBox onkeyup
         TextBox tb = GetTextBoxControl();
         tb.Attributes["onkeypress"] += string.Format("skm_CheckCapsLock( event, '{0}', {1});", this.ClientID, this.WarningDisplayTime);
      }
   }
}

The GetTextBoxControl method (not shown in this article) returns a reference to the TextBox control specified by the TextBoxControlId property. This referenced TextBox has its Attributes collection updated to include an onkeypress event handler that calls the JavaScript function skm_CheckCapsLock. The skm_CheckCapsLock function (which we'll examine shortly), is passed three input parameters:

  • event - information about the keypress event, including what key was pressed and whether the Shift key was depressed.
  • The value of the WarnWhenCapsLockIsOn's ClientID property - we need to supply the client-side id of the WarnWhenCapsLockIsOn control so that it can be displayed or hidden, depending on whether the user has Caps Lock on.
  • WarningDisplayTime - the number of milliseconds to display the Caps Lock warning; defaults to 2500 milliseconds (2.5 seconds).

The WarnWhenCapsLockIsOn control is one of a few controls in my open-source control library, skmControls2. Another control in the same library is the TextBoxCounter control, which interactively displays how many characters the user has currently typed into a given textbox. (For more information on the TextBoxCounter control, read: Creating a TextBox Word / Character Counter Control.) The TextBoxCounter control requires a bit of JavaScript, and that JavaScript is already defined in a file named skmControls2.js. This file is compiled as an embedded resource in the assembly and is loaded into the ASP.NET page on which the TextBoxCounter or WarnWhenCapsLockIsOn controls are used via a call to the GetWebResourceUrl method. For more information on this technique see: Accessing Embedded Resources through a URL using WebResource.axd.

Because the skmControls2 library already has a JavaScript file, I decided to place the skm_CheckCapsLock function (and ancillary helper functions) there. It is injected into the ASP.NET page in the OnPreRender method (see step 1 in the comments in OnPreRender).

Determining Whether Caps Lock is On
When the keypress event is raised in client-side script, the event object contains information as to what key was pressed and whether the Shift key was depressed (along with whether Alt and Ctrl were depressed). It does not, however, indicate whether Caps Lock was on. The good news is that with a bit of code we can determine whether Caps Lock is on. If the user has entered a capital letter and the Shift key is not depressed, then Caps Lock must be on; likewise, if the user enters a lowercase letter and the Shift key is depressed, then Caps Lock is on.

The skm_CheckCapsLock function determines whether Caps Lock is on and, if so, calls the skm_ShowCapsWarning function, which displays the WarnWhenCapsLockIsOn control for a specified interval. If Caps Lock is not on then the skm_HideCapsWarning function is called, which hides the WarnWhenCapsLockIsOn control. The skm_CheckCapsLock function uses a modified version of a script created by John G. Wang, available online at http://javascript.internet.com/forms/check-cap-locks.html.

function skm_CheckCapsLock( e, warnId, dispTime ) {
   var myKeyCode = 0;
   var myShiftKey = e.shiftKey;
   
   if ( document.all ) {
      // Internet Explorer 4+
      myKeyCode = e.keyCode;
   } else if ( document.getElementById ) {
      // Mozilla / Opera / etc.
      myKeyCode = e.which;
   }
   
   if ((myKeyCode >= 65 && myKeyCode <= 90 ) || (myKeyCode >= 97 && myKeyCode <= 122)) {
      if (
         // Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
         ( (myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey )

         ||

         // Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
         ( (myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey )
       )
      {
         skm_ShowCapsWarning(warnId, dispTime);
      }
      else {
         skm_HideCapsWarning(warnId);
      }
   }
}

The keen reader will note that this check doesn't really identify when Caps Lock is on or off. Rather, it identifies if Caps Lock is on or off when typing in an alphabetic character. If the user types in the number "9" or presses the left arrow, the first conditional statement will evaluate to false. In other words, the skm_ShowCapsWarning or skm_HideCapsWarning functions are only called when the user enters an alphabetic character.

The skm_ShowCapsWarning and skm_HideCapsWarning functions are not shown in this article; you'll have to download the source code to inspect them. They're both fairly straightforward: both reference the WarnWhenCapsLockIsOn control and then set the visibility and display properties to show or hide the warning message. The only trickiness deals with the code that displays the warning for at most a specified number of milliseconds after the user types in with Caps Lock on. Specifically, these functions use the JavaScript setTimeout and clearTimeout methods. For more information on these functions, see the JavaScript Timing Events tutorials at W3 Schools.

Using the WarnWhenCapsLockIsOn Control in an ASP.NET Web Page
The download available at the end of this article includes the complete source code for the WarnWhenCapsLockIsOn controls, as well as a demo ASP.NET website. To use the skmControls2 controls in an ASP.NET website, copy the DLL to the website's /Bin directory and then add the following @Register directive to the tops of the .aspx pages where you want to use the controls:

<%@ Register Assembly="skmControls2" Namespace="skmControls2" TagPrefix="skm" %>

(Alternatively, you can add this @Register directive in the Web.config file so that you do not need to add it to every ASP.NET page that uses the controls. See Tip/Trick: How to Register User Controls and Custom Controls in Web.config.)

The demo included in the download has an ASP.NET page that shows using the WarnWhenCapsLockIsOn control in two scenarios: on a stand-alone TextBox and on the Password TextBox in the Login control. Let's look at the stand-alone TextBox example first:

<b>Please enter your name:</b>
<asp:TextBox ID="YourName" runat="server"></asp:TextBox>

<skm:WarnWhenCapsLockIsOn runat="server" ID="WarnOnYourName"
           CssClass="CapsLockWarning" TextBoxControlId="YourName"
           WarningDisplayTime="5000"><b>Warning:</b> Caps Lock is on.</skm:WarnWhenCapsLockIsOn>

<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />

The declarative markup above shows three controls: a TextBox (YourName); a WarnWhenCapsLockIsOn control; and a Button Web control. The WarnWhenCapsLockIsOn control is configured to display the message "Warning: Caps Lock is on" when the user types into the YourName textbox with Caps Lock on. It uses the CSS class CapsLockWarning for its styling, which I've defined on the page; the class specifies a light yellow background, padding, centered text, and a red border. The warning message is displayed for (at most) five seconds.

The following screen shot shows the demo page in action. Note that when Caps Lock is on and an alphabetic character is typed, the warning is displayed. This warning immediately disappears when Caps Lock is turned off and another alphabetic character is typed, or after five seconds, whatever comes first.

A warning is displayed when typing in the textbox with Caps Lock on.

This demo also shows how to apply the WarnWhenCapsLockIsOn control to the Password TextBox of a Login control. Start by adding a Login control to the page and then, from the Designer, select the "Convert to Template" from its smart tag. This will convert the Login control into a template, at which point you can add the WarnWhenCapsLockIsOn control in the Login user interface as needed, referencing the Password TextBox (whose ID property is "Password"). Be sure to put the WarnWhenCapsLockIsOn control within the Login control's template so that it can "see" the Password TextBox.

The WarnWhenCapsLockIsOn control can also be used in a Login control.

Happy Programming!

  • By Scott Mitchell
  • 크리에이티브 커먼즈 라이선스
    Creative Commons License


    Posted by tornado
     
    출처 : http://msdn.microsoft.com/ko-kr/library/cc438020(VS.71).aspx


    동적으로 웹 서버 컨트롤 템플릿 만들기

    여러 가지 이유로 인해, 런타임 전에는 필요한 템플릿과 이 템플릿에 포함해야 할 텍스트나 컨트롤을 알 수 없는 경우도 있습니다. 이러한 경우에는 코드를 사용하여 동적으로 템플릿을 만들 수 있어야 합니다.

    참고   템플릿을 Web Forms 사용자 정의 컨트롤로 만들어 이 템플릿을 페이지에 있는 컨트롤에 동적으로 바인딩해도 됩니다. 자세한 내용은 템플릿 기반 사용자 정의 컨트롤 만들기를 참조하십시오.

    템플릿을 사용하는 모든 컨트롤(DataList, RepeaterDataGrid 컨트롤)에 대해 코드를 사용하여 템플릿을 만들 수 있습니다. DataGrid 컨트롤의 경우, 다른 두 컨트롤에 대한 행 형식의 템플릿을 사용하지 않고 열을 정의하는 템플릿을 사용합니다.

    참고   DataGrid 컨트롤에 대한 템플릿 열을 만들 때는 몇 가지 차이점이 있습니다. 자세한 내용은 프로그래밍 방식으로 DataGrid 컨트롤에 템플릿 만들기를 참조하십시오.

    템플릿 클래스 만들기

    동적 템플릿을 만들려면 필요할 때 인스턴스화할 수 있는 템플릿 클래스를 만듭니다.

    참고   Visual Basic .NET에서 클래스를 만드는 데 대한 배경 설명을 보려면 클래스의 이해를 참조하십시오. Visual C# .NET의 경우에는 클래스를 참조하십시오.

    템플릿 클래스를 만들려면

    1. System.Web.UI 네임스페이스의 ITemplate 인터페이스를 구현하는 새 클래스를 만듭니다.
    2. 필요한 경우, 클래스에서 만들 템플릿의 형식(ItemTemplate, AlternatingItemTemplate 등)을 결정할 때 사용되는 값을 클래스의 생성자에 전달합니다.
         생성자에 템플릿 형식을 전달할 때 형식 안전성을 유지하려면 ListItemType 형식을 사용하여 생성자에 매개 변수를 추가하면 됩니다. ListItemType 열거형에서는 Repeater, DataListDataGrid 컨트롤에 대해 사용 가능한 템플릿 형식을 정의합니다.
    3. ITemplate 인터페이스의 유일한 멤버인 InstantiateIn 메서드를 클래스에 구현합니다. 이 메서드를 통해 텍스트 및 컨트롤의 인스턴스를 지정된 컨테이너에 삽입할 수 있습니다.
    4. InstantiateIn 메서드에서 템플릿 항목에 대한 컨트롤을 만들고 속성을 설정한 다음 부모의 Controls 컬렉션에 추가합니다. InstantiateIn 메서드에 전달된 참조를 통해 부모 컨트롤에 액세스할 수 있습니다.
      참고   Controls 컬렉션에 정적 텍스트를 직접 추가할 수는 없지만, Literal 컨트롤 또는 LiteralControl 컨트롤 등의 컨트롤을 만들고 Text 속성을 설정한 다음 이 컨트롤을 부모 컬렉션에 추가할 수는 있습니다.

      다음 예제에서는 일부 정적 텍스트("Item number:") 및 카운터를 표시하는 완전한 템플릿 클래스를 보여 줍니다. 카운터는 클래스에 대해 itemcount라는 공유 또는 정적 값(사용하는 언어에 따라 다름)으로 보존되며 새 항목이 만들어질 때마다 크기가 증가합니다.

      클래스에서는 만들어지는 템플릿의 형식을 나타내기 위해 ListItemType 열거형 값을 받는 명시적 생성자를 정의합니다. 만들어지는 템플릿의 형식에 따라 코드에서 서로 다른 종류의 컨트롤이 만들어지고 이 컨트롤은 부모 컨트롤의 Controls 컬렉션에 추가됩니다. 마지막으로, 대체 항목 템플릿에 대해 서로 다른 배경색을 가진 HTML 테이블이 만들어집니다.

      ' Visual Basic
      Private Class MyTemplate
         Implements ITemplate
         Shared itemcount As Integer = 0
         Dim TemplateType As ListItemType
      
         Sub New(ByVal type As ListItemType)
            TemplateType = type
         End Sub
      
         Sub InstantiateIn(ByVal container As Control) _
            Implements ITemplate.InstantiateIn
            Dim lc As New Literal()
            Select Case TemplateType
               Case ListItemType.Header
                  lc.Text = "<TABLE border=1><TR><TH>Items</TH></TR>"
               Case ListItemType.Item
                  lc.Text = "<TR><TD>Item number: " & itemcount.ToString _
                     & "</TD></TR>"
               Case ListItemType.AlternatingItem
                  lc.Text = "<TR><TD bgcolor=lightblue>Item number: " _
                     & itemcount.ToString & "</TD></TR>"
               Case ListItemType.Footer
                  lc.Text = "</TABLE>"
            End Select
            container.Controls.Add(lc)
            itemcount += 1
         End Sub
      End Class
      
      // C#
      public class MyTemplate : ITemplate
      {
         static int itemcount = 0;
         ListItemType templateType;
      
         public MyTemplate(ListItemType type)
         {
            templateType = type;
         }
      
         public void InstantiateIn(System.Web.UI.Control container)
         {
            Literal lc = new Literal();
            switch( templateType )
            {
               case ListItemType.Header:
                  lc.Text = "<TABLE border=1><TR><TH>Items</TH></TR>";
                  break;
               case ListItemType.Item:
                  lc.Text = "<TR><TD>Item number: " + itemcount.ToString() +
                     "</TD></TR>";
                  break;
               case ListItemType.AlternatingItem:
                  lc.Text = "<TR><TD bgcolor=lightblue>Item number: " + 
                     itemcount.ToString() + "</TD></TR>";
                  break;
               case ListItemType.Footer:
                  lc.Text = "</TABLE>";
                  break;
            }
            container.Controls.Add(lc);
            itemcount += 1;
         }
      }

    동적 템플릿 사용

    사용할 수 있는 동적 템플릿이 있으면 이 템플릿을 코드에서 인스턴스화할 수 있습니다.

    참고   DataGrid 컨트롤에서 하나의 동적 템플릿을 열로 사용하여 작업하려면 프로그래밍 방식으로 DataGrid 컨트롤에 템플릿 만들기를 참조하십시오.

    동적 템플릿을 사용하려면

    1. 동적 템플릿의 인스턴스를 만들고 적합한 경우 여기에 항목 형식의 값을 전달합니다.
    2. Repeater 또는 DataList 컨트롤의 템플릿 속성 중 하나에 ItemTemplate, AlternatingItemTemplate, HeaderTemplate 등의 인스턴스를 할당합니다.

      다음 예제에서는 동적 템플릿을 Repeater 컨트롤과 함께 사용하는 방법을 보여 줍니다. 이 예제에서는 페이지가 로드되는 동안 컨트롤이 데이터 소스에 바인딩되기 전에 템플릿이 인스턴스화됩니다.

      ' Visual Basic
      Private Sub Page_Load(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load
         Repeater1.HeaderTemplate = New MyTemplate(ListItemType.Header)
         Repeater1.ItemTemplate = New MyTemplate(ListItemType.Item)
         Repeater1.AlternatingItemTemplate = _
            New MyTemplate(ListItemType.AlternatingItem)
         Repeater1.FooterTemplate = New MyTemplate(ListItemType.Footer)
         SqlDataAdapter1.Fill(DsCategories1)
         Repeater1.DataBind()
      End Sub
      
      // C#
      private void Page_Load(object sender, System.EventArgs e)
      {
         Repeater1.HeaderTemplate = new MyTemplate(ListItemType.Header);
         Repeater1.ItemTemplate = new MyTemplate(ListItemType.Item);
         Repeater1.AlternatingItemTemplate = 
            new MyTemplate(ListItemType.AlternatingItem);
         Repeater1.FooterTemplate = new MyTemplate(ListItemType.Footer);
         sqlDataAdapter1.Fill(dsCategories1);
         Repeater1.DataBind();
      }

    템플릿에 데이터 바인딩 추가

    템플릿 클래스 안에서 데이터에 액세스할 수 있는 방법은 클래스를 만드는 방법에 따라 다양합니다. 이 중에서 페이지 아키텍처 자체에서 데이터 바인딩을 구현하는 것이 가장 좋습니다. 템플릿에 컨트롤을 추가하면 이러한 컨트롤의 DataBinding 이벤트에 대한 처리기도 추가됩니다. 이 이벤트는 템플릿 항목과 해당 템플릿과 관련된 컨트롤이 모두 만들어진 후에 발생하며 데이터를 페치하여 컨트롤에서 사용할 수 있도록 합니다.

    참고   템플릿에 컨트롤을 만들 때 디자인 타임에 템플릿을 정의할 때처럼 데이터 바인딩 식을 문자열로 포함할 수 없습니다. 데이터 바인딩 식은 템플릿이 만들어지기 전에 발생하는 페이지 처리 과정 단계에서 코드로 변환되기 때문입니다.

    DataBinding 이벤트에 대한 처리기에서 컨트롤의 내용을 조작할 수 있습니다. 필수적인 것은 아니지만, 보통 임의의 위치에서 데이터를 페치(fetch)하여 컨트롤의 Text 속성에 할당합니다.

    참고   Web Forms 페이지에서의 데이터 바인딩 작업에 대한 배경 설명은 Web Forms 데이터 바인딩을 참조하십시오.

    동적 템플릿에 데이터 바인딩을 추가하려면 다음 작업을 수행해야 합니다.

    • 템플릿에서 만든 컨트롤에 데이터 바인딩 이벤트 처리기를 추가합니다.
    • 바인딩 대상이 되는 처리기를 만듭니다. 바인딩할 데이터를 이 처리기에서 가져온 다음, 바인딩되는 컨트롤의 해당 속성에 할당합니다.

    데이터 바인딩 이벤트 처리기를 추가하려면

    • 동적 템플릿에 컨트롤을 만든 후에 표준 명령을 사용하여 컨트롤의 DataBinding 이벤트를 나중에 만들 메서드에 바인딩합니다.
      참고   동적으로 이벤트 처리기를 추가하는 방법에 대한 자세한 내용은 AddHandler 및 RemoveHandler(Visual Basic용)와 이벤트 자습서(Visual C#용)를 참조하십시오.

      다음 예제에서는 새로 만든 컨트롤을 TemplateControl_DataBinding 메서드에 바인딩하는 템플릿 클래스의 코드를 보여 줍니다.

      ' Visual Basic
      Dim lc As New Literal()
         Case ListItemType.Item
         lc.Text = "<TR><TD>"
         AddHandler lc.DataBinding, AddressOf TemplateControl_DataBinding
      
      // C#
      Literal lc = new Literal();
      case ListItemType.Item:
         lc.Text = "<TR><TD>";
         lc.DataBinding += new EventHandler(TemplateControl_DataBinding);
         break;

      이 예제에서 리터럴 컨트롤의 Text 속성에 추가하는 텍스트는 이전의 예제에 나온 텍스트와는 다릅니다. 여기에는 표 행의 시작 부분과 항목 템플릿에 대한 셀만 포함되어 있습니다. 데이터 바인딩 이벤트 처리기에서 셀과 행을 완성합니다.

    다음 단계에서는 컨트롤에 데이터가 바인딩될 때 호출되는 이벤트 처리기를 만듭니다.

    DataBinding 이벤트에 대한 처리기를 만들려면

    1. 템플릿 클래스를 구성하며 이 클래스의 InstantiateIn 등과 같은 다른 메서드와 동일한 수준의 역할을 수행할 메서드를 만듭니다. 처리기의 이름은 이벤트 처리기를 바인딩할 때 사용했던 이름과 같아야 합니다. 이 이벤트에는 다음과 같은 서명이 있어야 합니다.
      ' Visual Basic
      Private Sub TemplateControl_DataBinding(ByVal sender As Object, _
         ByVal e As System.EventArgs)
      
      // C#
      private void TemplateControl_DataBinding(object sender,
         System.EventArgs e)
    2. 다음을 수행하여 현재 템플릿 항목에 대한 데이터가 포함된 DataItem 개체의 참조를 가져옵니다.
      1. 템플릿 항목에 대한 참조를 가져옵니다. 참조를 보관할 변수를 만든 다음 이 변수에 컨트롤의 NamingContainer 속성에서 가져오는 값을 할당합니다.
      2. 이 참조를 사용하여 이름 지정 컨테이너(템플릿 항목)의 DataItem 속성을 가져옵니다.
      3. DataItem 개체에서 데이터 열 등의 개별 데이터 요소를 추출하고, 이 요소를 사용하여 바인딩 대상 컨트롤의 속성을 설정합니다.

        다음 코드에서는 동적 템플릿 안에서 데이터 바인딩을 수행하는 방법 중 하나를 보여 줍니다. 여기에서는 Repeater 컨트롤의 템플릿에서 만들어지는 Literal 컨트롤에 대한 데이터 바인딩 이벤트 처리기의 전체 코드를 보여 줍니다.

        ' Visual Basic
        Private Sub TemplateControl_DataBinding(ByVal sender As Object, _
           ByVal e As System.EventArgs)
           Dim lc As Literal
           lc = CType(sender, Literal)
           Dim container As RepeaterItem
           container = CType(lc.NamingContainer, RepeaterItem)
           lc.Text &= DataBinder.Eval(container.DataItem, "CategoryName")
           lc.Text &= "</TD></TR>"
        End Sub
        
        // C#
        private void TemplateControl_DataBinding(object sender,
        System.EventArgs e)
        {
           Literal lc;
           lc = (Literal) sender;
           RepeaterItem container = (RepeaterItem) lc.NamingContainer;
           lc.Text += DataBinder.Eval(container.DataItem, "CategoryName");
           lc.Text += "</TD></TR>";
        }
        참고   템플릿에 여러 형식의 컨트롤이 있는 경우 각 컨트롤 형식마다 서로 다른 데이터 바인딩 이벤트 처리기를 만들어야 합니다.

    참고 항목

    크리에이티브 커먼즈 라이선스
    Creative Commons License


    Posted by tornado
     


    출처 : http://blog.naver.com/devstory/130038823596



     

    객체의 좌표 값 추출

     

    익스플로러 6 / 파이어폭스 2 에서 테스트 되었습니다.

     

    <HTML>
    <HEAD>
     <SCRIPT type = "text/javascript">
      /**
       * 좌표 값을 측정한다.
       *
       * @param obj 측정 요망 객체
       */
      function getBounds( obj ) {
       var ret = new Object();

       if(document.all) {
        var rect = obj.getBoundingClientRect();
        ret.left = rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft);
        ret.top = rect.top + (document.documentElement.scrollTop || document.body.scrollTop);
        ret.width = rect.right - rect.left;
        ret.height = rect.bottom - rect.top;
       } else {
        var box = document.getBoxObjectFor(obj);
        ret.left = box.x;
        ret.top = box.y;
        ret.width = box.width;
        ret.height = box.height;
       }

       return ret;
      }

      /**
       * 버튼 객체의 좌표 추출
       */
      function getThisCoordi() {
       var obj = getBounds( document.getElementById("testBtn") );

       alert( "left : " + obj.left + ", top : " + obj.top + ", width : " + obj.width + ", height : " + obj.height );
      }
     </SCRIPT>
    </HEAD>
    <BODY>
    <P>&nbsp;</P>
    <CENTER><INPUT type = "button" id = "testBtn" value = "테스트" onClick = "getThisCoordi()"/></CENTER>
    </BODY>
    </HTML>

    크리에이티브 커먼즈 라이선스
    Creative Commons License


    Posted by tornado
     

    출처 : http://blog.naver.com/devstory/130038823596


    객체의 좌표 값 추출

     

    익스플로러 6 / 파이어폭스 2 에서 테스트 되었습니다.

     

    <HTML>
    <HEAD>
     <SCRIPT type = "text/javascript">
      /**
       * 좌표 값을 측정한다.
       *
       * @param obj 측정 요망 객체
       */
      function getBounds( obj ) {
       var ret = new Object();

       if(document.all) {
        var rect = obj.getBoundingClientRect();
        ret.left = rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft);
        ret.top = rect.top + (document.documentElement.scrollTop || document.body.scrollTop);
        ret.width = rect.right - rect.left;
        ret.height = rect.bottom - rect.top;
       } else {
        var box = document.getBoxObjectFor(obj);
        ret.left = box.x;
        ret.top = box.y;
        ret.width = box.width;
        ret.height = box.height;
       }

       return ret;
      }

      /**
       * 버튼 객체의 좌표 추출
       */
      function getThisCoordi() {
       var obj = getBounds( document.getElementById("testBtn") );

       alert( "left : " + obj.left + ", top : " + obj.top + ", width : " + obj.width + ", height : " + obj.height );
      }
     </SCRIPT>
    </HEAD>
    <BODY>
    <P>&nbsp;</P>
    <CENTER><INPUT type = "button" id = "testBtn" value = "테스트" onClick = "getThisCoordi()"/></CENTER>
    </BODY>
    </HTML>

    크리에이티브 커먼즈 라이선스
    Creative Commons License


    Posted by tornado
     
    Jquery 에 달력만 있는줄 알았는데, 시간 선택하는 녀석도 있었습니다.

    목마른 놈이 우물 판다더니... 덕분에 일 하나 주워 먹었다~


    첫번째 :

    [출처] http://www.jnathanson.com/index.cfm?page=jquery/clockpick/ClockPick#config

    BGIFramework 라는 js 를 제공해 주는데, 이것을 같이 쓰면 CheckBox 같은것에 겹쳐지지 않는다.

    UI 적으로는 아주 좋지는 않지만 쓰기에는 편리함.



    두번째 :

    [출처] http://haineault.com/media/jquery/ui-timepickr/page/#d-demo-wrapper-1

    요거는 모양도 이쁘고, 테마도 지원된다.

    SelectBox, CheckBox 등이 있으면 겹쳐지는 문제가 발생.

    고치려고 하니, Jquery 초보라 힘듬 -.-;








    크리에이티브 커먼즈 라이선스
    Creative Commons License


    Posted by tornado