Asp.net自定义控件和javascript函数

发布于 2024-12-07 14:37:08 字数 6262 浏览 0 评论 0原文

有一个名为 PhoneTextBox2 的自定义 asp.net 控件。它使用 ext.net 库,但我不在乎。

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PhoneTextBox2.ascx.cs"
    Inherits="Loginet.Web.Controls.PhoneTextBox2" %>

 <script type="text/javascript">
               var <%=ClientID%>_getNumber = function () {
                return alert( 'some value');
            }
        </script>
<ext:CompositeField runat="server" ID="eCompositeField">
        <Items>
            <ext:Label ID="PhoneBoxTitle" runat="server" />
        </Items>
</ext:CompositeField>

在aspx页面中,我通过这种方式调用PhoneTextBox2的javascript方法

<uc:PhoneTextBox2 runat="server" ID="txtb" />
<ext:Button Text="test" runat="server">
        <Listeners>
            <Click Handler="#{txtb}_getNumber();"></Click>
        </Listeners>
</ext:Button>

#{txtb}_getNumber() 是javascript函数的唯一名称,而#{txtb } - 是 PhoneTextBox2 的唯一名称。

如何通过dot调用getNumber?

<Click Handler="#{txtb}.getNumber();">

更新:

    public partial class PhoneTextBox2 : System.Web.UI.UserControl {
            /// <summary>
            /// Допускаются ли, чтобы все поля были пустыми
            /// True - Допускаются. Используется тогда, когда данные из этого контрола необязательные.
            /// </summary>
            public bool EnableEmptyValues { get; set; }
            public string Title { get; set; }
            protected void Page_Load(object sender, EventArgs e) {

                txtCountryCode.AllowBlank = EnableEmptyValues;
                txtCityCode.AllowBlank = EnableEmptyValues;
                txtMainPhoneNumber.AllowBlank = EnableEmptyValues;

                if (!IsPostBack && !Ext.Net.ExtNet.IsAjaxRequest) {
                    PhoneBoxTitle.Text = Title;
                    if (!string.IsNullOrWhiteSpace(DataSource)) {

                        string[] phoneNumberArray = DataSource.Split('-');
                        if (phoneNumberArray.Length >= _standartDimension) {
                            txtCountryCode.Text = phoneNumberArray[0];
                            if (txtCountryCode.Text[0] == _plus) {
                                txtCountryCode.Text = txtCountryCode.Text.Remove(0, 1);
                            }
                            txtCityCode.Text = phoneNumberArray[1];
                            txtMainPhoneNumber.Text = phoneNumberArray[2];
                            if (phoneNumberArray.Length >= _extraDimension) {
                                txtExtraPhoneNumber.Text = phoneNumberArray[3];
                            }
                        }
                    }
                }
            }


            public string DataSource { get; set; }


            private const string _phoneNumberMask = "+{0}-{1}-{2}-{3}";
            private const char _plus = '+';
            private const int _standartDimension = 3;
            private const int _extraDimension = 4;

            public string Number {
                get {
                    if (!string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
                        !string.IsNullOrWhiteSpace(txtCityCode.Text) &&
                        !string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text)) {

                        //Если добавочный номер пустой, то возвратить значения без него
                        if (!string.IsNullOrWhiteSpace(txtExtraPhoneNumber.Text))
                            return string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, txtExtraPhoneNumber.Text);

                        string phoneNumber = string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, string.Empty);
                        return phoneNumber.Remove(phoneNumber.Length - 1);

                    }
                    return string.Empty;
                }
            }


            public bool IsEmpty {
                get {
                    return (string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
                            string.IsNullOrWhiteSpace(txtCityCode.Text) &&
                            string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text) &&
                            string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text));
                }
            }




            /// <summary>
            /// Validate 
            /// </summary>
            public void Validate() {
                if (EnableEmptyValues) {
                    if (!IsEmpty && Number == string.Empty)
                        MarkInvalid();
                    else
                        MarkValid();
                }

                else {
                    if (IsEmpty)
                        MarkInvalid();
                    else {
                        if (Number == string.Empty)
                            MarkInvalid();
                        else
                            MarkValid();
                    }
                }
            }

            public void MarkInvalid(string msg = null) {
                txtCountryCode.MarkInvalid(msg);
                txtCityCode.MarkInvalid(msg);
                txtMainPhoneNumber.MarkInvalid(msg);
                txtExtraPhoneNumber.MarkInvalid(msg);

            }

            public void MarkValid() {
                txtCountryCode.MarkAsValid();
                txtCityCode.MarkAsValid();
                txtMainPhoneNumber.MarkAsValid();
                txtExtraPhoneNumber.MarkAsValid();
            }


             public const string InvalidCheckBoxCssStyle = "border-color:#C30; background:  url('/extjs/resources/images/default/grid/invalid_line-gif/ext.axd') repeat-x scroll center bottom white; width: 40px !important;";
         public const string ValidCheckBoxCssStyle = "border-color:#000; background: none repeat scroll 0 0 transparent;";
}

请注意,在我的情况中,由于 ext.net 的功能,我无法使用服务器端属性Number。因此我需要使用javascript来获取Number

There's a custom a asp.net control named PhoneTextBox2. It uses ext.net library, but I doesn't matter.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PhoneTextBox2.ascx.cs"
    Inherits="Loginet.Web.Controls.PhoneTextBox2" %>

 <script type="text/javascript">
               var <%=ClientID%>_getNumber = function () {
                return alert( 'some value');
            }
        </script>
<ext:CompositeField runat="server" ID="eCompositeField">
        <Items>
            <ext:Label ID="PhoneBoxTitle" runat="server" />
        </Items>
</ext:CompositeField>

In aspx page I call the javascript method of PhoneTextBox2 by this way

<uc:PhoneTextBox2 runat="server" ID="txtb" />
<ext:Button Text="test" runat="server">
        <Listeners>
            <Click Handler="#{txtb}_getNumber();"></Click>
        </Listeners>
</ext:Button>

#{txtb}_getNumber() is the unique name of the javascript function, and #{txtb} - is the unique name of the PhoneTextBox2.

What can I do to call getNumber by dot?

<Click Handler="#{txtb}.getNumber();">

UPDATE:

    public partial class PhoneTextBox2 : System.Web.UI.UserControl {
            /// <summary>
            /// Допускаются ли, чтобы все поля были пустыми
            /// True - Допускаются. Используется тогда, когда данные из этого контрола необязательные.
            /// </summary>
            public bool EnableEmptyValues { get; set; }
            public string Title { get; set; }
            protected void Page_Load(object sender, EventArgs e) {

                txtCountryCode.AllowBlank = EnableEmptyValues;
                txtCityCode.AllowBlank = EnableEmptyValues;
                txtMainPhoneNumber.AllowBlank = EnableEmptyValues;

                if (!IsPostBack && !Ext.Net.ExtNet.IsAjaxRequest) {
                    PhoneBoxTitle.Text = Title;
                    if (!string.IsNullOrWhiteSpace(DataSource)) {

                        string[] phoneNumberArray = DataSource.Split('-');
                        if (phoneNumberArray.Length >= _standartDimension) {
                            txtCountryCode.Text = phoneNumberArray[0];
                            if (txtCountryCode.Text[0] == _plus) {
                                txtCountryCode.Text = txtCountryCode.Text.Remove(0, 1);
                            }
                            txtCityCode.Text = phoneNumberArray[1];
                            txtMainPhoneNumber.Text = phoneNumberArray[2];
                            if (phoneNumberArray.Length >= _extraDimension) {
                                txtExtraPhoneNumber.Text = phoneNumberArray[3];
                            }
                        }
                    }
                }
            }


            public string DataSource { get; set; }


            private const string _phoneNumberMask = "+{0}-{1}-{2}-{3}";
            private const char _plus = '+';
            private const int _standartDimension = 3;
            private const int _extraDimension = 4;

            public string Number {
                get {
                    if (!string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
                        !string.IsNullOrWhiteSpace(txtCityCode.Text) &&
                        !string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text)) {

                        //Если добавочный номер пустой, то возвратить значения без него
                        if (!string.IsNullOrWhiteSpace(txtExtraPhoneNumber.Text))
                            return string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, txtExtraPhoneNumber.Text);

                        string phoneNumber = string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, string.Empty);
                        return phoneNumber.Remove(phoneNumber.Length - 1);

                    }
                    return string.Empty;
                }
            }


            public bool IsEmpty {
                get {
                    return (string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
                            string.IsNullOrWhiteSpace(txtCityCode.Text) &&
                            string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text) &&
                            string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text));
                }
            }




            /// <summary>
            /// Validate 
            /// </summary>
            public void Validate() {
                if (EnableEmptyValues) {
                    if (!IsEmpty && Number == string.Empty)
                        MarkInvalid();
                    else
                        MarkValid();
                }

                else {
                    if (IsEmpty)
                        MarkInvalid();
                    else {
                        if (Number == string.Empty)
                            MarkInvalid();
                        else
                            MarkValid();
                    }
                }
            }

            public void MarkInvalid(string msg = null) {
                txtCountryCode.MarkInvalid(msg);
                txtCityCode.MarkInvalid(msg);
                txtMainPhoneNumber.MarkInvalid(msg);
                txtExtraPhoneNumber.MarkInvalid(msg);

            }

            public void MarkValid() {
                txtCountryCode.MarkAsValid();
                txtCityCode.MarkAsValid();
                txtMainPhoneNumber.MarkAsValid();
                txtExtraPhoneNumber.MarkAsValid();
            }


             public const string InvalidCheckBoxCssStyle = "border-color:#C30; background:  url('/extjs/resources/images/default/grid/invalid_line-gif/ext.axd') repeat-x scroll center bottom white; width: 40px !important;";
         public const string ValidCheckBoxCssStyle = "border-color:#000; background: none repeat scroll 0 0 transparent;";
}

Note, in my case I can't use the server side property Number because of feature of ext.net. Therefore I need to use javascript to get Number.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦回梦里 2024-12-14 14:37:08

Handler 指向 .NET 自定义方法/委托,并且它们的名称中不能包含句号。


您可以扩展任何对象类型,例如:

String.prototype.getNumber = function() { 
  alert('here: ' + this);
};

然后

'txtElement'.getNumber();

您可以将代码更改为

<Click Handler="'{txtb}'.getNumber();">

Handler points to a .NET custom method/delegate, and they can't have period signs in their names.


You can extend any object type, for example:

String.prototype.getNumber = function() { 
  alert('here: ' + this);
};

and then

'txtElement'.getNumber();

so you can change your code to

<Click Handler="'{txtb}'.getNumber();">
好倦 2024-12-14 14:37:08

无需为您的 JavaScript 函数分配动态名称。只需在创建第一个控件时注册该方法,并在创建该控件的下一个实例时检查该方法是否已注册。

注册脚本块:

if (!Page.ClientScript.IsClientScriptBlockRegistered("getNumberScript"))
    Page.ClientScript.RegisterClientScriptBlock(GetType(), "getNumberScript", "getNumber = function () { return alert( 'some value'); }", true);

注册包含文件(外部js):

if (!Page.ClientScript.IsClientScriptIncludeRegistered("getNumberScript"))
    Page.ClientScript.RegisterClientScriptInclude("getNumberScript", "getNumberScript.js");

There's no need to assign a dynamic name to your javascript function. Simply register the method when the first control is created, and check to see if it's already registered when the next instance of the control is created.

Registering a script block:

if (!Page.ClientScript.IsClientScriptBlockRegistered("getNumberScript"))
    Page.ClientScript.RegisterClientScriptBlock(GetType(), "getNumberScript", "getNumber = function () { return alert( 'some value'); }", true);

Registering an include file (external js):

if (!Page.ClientScript.IsClientScriptIncludeRegistered("getNumberScript"))
    Page.ClientScript.RegisterClientScriptInclude("getNumberScript", "getNumberScript.js");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文