Подтвердить что ты не робот

Есть ли элемент управления UpDown для ASP.NET?

Можно ли использовать числовое обновление в ASP.NET без использования JavaScript?

А если нет, есть ли альтернатива?

4b9b3361

Ответ 1

Я пытался сделать то же самое, и оказалось, что в текстовом поле asp есть опция. у меня получилось так:

<asp:TextBox TextMode="Number" runat="server" min="0" max="20" step="1"/>

это дало мне текстовое поле, которое, когда мышь наводит курсор на него или получает фокус, показывает элементы управления вверх-вниз и допускает только цифры от мин до макс. это работает так же, как

<input type="number" min="0" max="20" step="1" />

Ответ 2

Пожалуйста, посмотрите в Ajax Control Toolkit

http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/NumericUpDown/NumericUpDown.aspx

<ajaxToolkit:NumericUpDownExtender ID="NUD1" runat="server"
    TargetControlID="TextBox1" 
    Width="100"
    RefValues="January;February;March;April"
    TargetButtonDownID="Button1"
    TargetButtonUpID="Button2"
    ServiceDownPath="WebService1.asmx"
    ServiceDownMethod="PrevValue"
    ServiceUpPath="WebService1.asmx"
    ServiceUpMethod="NextValue"
    Tag="1" />

Также рассмотрите возможность добавления ссылки с NuGet с помощью PM> Install-Package AjaxControlToolkit

Ответ 3

Я думаю, что следующий html может ответить на ваш вопрос:

<head runat="server">
    <title>Numeric Up Down</title>
    <script type="text/jscript">
        function Load() {
           /*numericUpDown1.value = or*/ document.getElementById("numericUpDown1").value = parseFloat(document.getElementById("<%=NumericUpDown1.ClientID%>").value);
        }
        function Change() {
           document.getElementById("<%=NumericUpDown1.ClientID%>").value = document.getElementById("numericUpDown1").value; //or numericUpDown1.value
        }
    </script>
</head>
<body onload="Load()">
    <form id="form1" runat="server">
    <div>
       <input type="number" id="numericUpDown1" onchange="Change()" />
       <asp:HiddenField ID="NumericUpDown1" runat="server" />
    </div>
</form>
</body>

И затем в коде на стороне сервера asp в С# или Visual Basic вы можете рассматривать этот HiddenField как NumericUpDown, но note, что его значение строка и not десятичный, например System.Windows.Forms.NumericUpDown, или float, или double, или int, поэтому вам придется проанализировать его на один из этих типов, для чего вам больше всего нужно.

Если вы хотите стиль с цифрой вверх, тогда в javascript это просто. Просто установите стиль document.getElementById( "numericUpDown1" )., Но если вы хотите сделать это с помощью кода на стороне сервера asp на С# или Visual Basic, то html должен быть другим:

<head runat="server">
    <title>Numeric Up Down</title>
    <script type="text/jscript">
        function Change() {
           document.getElementById("<%=NumericUpDown1.ClientID%>").value = document.getElementById("numericUpDown1").value; //or numericUpDown1.value
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <% this.Response.Write(string.Format("<input type='number' id='numericUpDown1' value='{0}' onchange='Change()' style='{1}' />", this.NumericUpDown1.Value, this.numericUpDown1Style)); %>
       <asp:HiddenField ID="NumericUpDown1" runat="server" />
    </div>
</form>
</body>

numericUpDown1Style - это защищенное поле, тип которого строка, определенная в коде сервера asp на С# или Visual Basic.

Если вы хотите присвоить ему класс, а не стиль, то html должен быть:

<head runat="server">
    <title>Numeric Up Down</title>
    <script type="text/jscript">
        function Change() {
           document.getElementById("<%=NumericUpDown1.ClientID%>").value = document.getElementById("numericUpDown1").value; //or numericUpDown1.value
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <% this.Response.Write(string.Format("<input type='number' id='numericUpDown1' value='{0}' onchange='Change()' class='{1}' />", this.NumericUpDown1.Value, this.numericUpDown1CssClass)); %>
       <asp:HiddenField ID="NumericUpDown1" runat="server" />
    </div>
</form>
</body>

numericUpDown1CssClass - это защищенное поле, тип которого строка, определенная в коде сервера asp на С# или Visual Basic.

Если вы хотите стилизовать его и дать ему класс, то html будет похож на html # 2 или html # 3, но единственное изменение будет в следующей строке:

<% this.Response.Write(string.Format("<input type='number' id='numericUpDown1' value='{0}' onchange='Change()' style='{1}' class='{2}' />", this.NumericUpDown1.Value, this.numericUpDown1Style, this.numericUpDown1CssClass)); %>

Я думаю, что вы знаете, что такое numericUpDown1Style и numericUpDown1CssClass из # 2 и # 3

РЕКОМЕНДУЕМЫЙ СОВЕТ:

Если ваш веб-сайт содержит множество числовых элементов управления сверху вниз, которые используются в вашем коде сервера ASP, и это невыгодно создавать все из них таким образом, то вы можете добавить новый элемент управления веб-пользователями на свой веб-сайт и назовите его "NumericUpDown". Затем в исходном html вы можете скопировать html # 1 или html # 2 или html # 3 или html # 4, которые я разместил выше (зависит от того, хотите ли вы стилизовать число вниз или нет или дать ему класс или нет, или оба или нет) с некоторыми удалениями и изменениями, поскольку это не "WebForm", а "Web User Control", и в коде сервера asp выполните следующие свойства (они находятся на С#, но если вы используете Visual Basic, я не думаю, что вам будет сложно перевести код):

    public decimal Value
    {
        get
        {
            return decimal.Parse(this.HiddenField.Value);
        }
        set
        {
            this.HiddenField.Value = value.ToString();
        }
    }
    //Like the System.Windows.Forms.NumericUpDown.Value, but if you dislike 'decimal', and you want other type, then you can change the return type and the type Parse.
//Note that the ID of the HiddenField is simply "HiddenField", and not "NumericUpDown1", so make sure in the Source html to rename "NumericUpDown1" to "HiddenField", but probably you would like a different ID, so if you gave it different ID, then ensure that in the code you refer this HiddenField with the ID you chose, and not "HiddenField" or "NumericUpDown1".

    //The following properties are for only if you want to style your Numeric Up Down:
    protected string style;
    public string Style
    {
        get
        {
            return this.style;
        }
        set
        {
            this.style = value;
        }
    }
    //If you chose, copied, pasted and changed html #2 or html #4, then don't forget to replace this.numericUpDown1Style to this.Style in the source html of the Web User Control.
    //Optional
    public Unit Width
    {
       get
       {
           int startIndex = this.style.IndexOf("width") + 6;
           if (index != -1)
           {
               int endIndex = this.style.IndexOf(';', startIndex);
               return Unit.Parse(this.style.Substring(startIndex, endIndex - startIndex));
           }
           return Unit.Empty;
       }
       set
       {
          if (this.style.Contains("width"))
          {
              this.style = this.style.Replace("width:" + this.Width.ToString() + ';', "width:" + value.ToString() + ';');
          }
          else
          {
              this.style += "width:" + value.ToString() + ';';
          }
       }
    }
//The same you can do with the Height property.
//You can replace all the style code with the CssClass code instead, or just add it:
protected string cssClass;
public string CssClass
{
    get
    {
        return this.cssClass;
    }
    set
    {
        this.cssClass = value;
    }
}
    //If you chose, copied, pasted and changed html #3 or html #4, then don't forget to replace this.numericUpDown1CssClass to this.CssClass in the source html of the Web User Control.

Если вы нарисуете NumericUpDown, то также знайте, что в каждом элементе управления ASP.NET вы можете ввести после своего ID.Style [ "style" ] = "value".

Если вы захотите сделать это с помощью NumericUpDown, измените тип защищенного поля стиль от строки до MyStyle

Существует определение MyStyle:

public class MyStyle
{
    internal string style;
    public string this[string style]
    {
        get
        {
            int startIndex = this.style.IndexOf(style) + style.Length + 1;
            int endIndex = this.style.IndexOf(';', startIndex);
            return this.style.Substring(startIndex, endIndex - startIndex)
        }
        set
        {
            this.style = this.style.Replace(style + ':' + this[style] + ';', style + ':' + value + ';')
        }
    }
}

Добавьте этот класс в Code of User User Control и измените свойство Style:

public string Styles
{
    get
    {
        return this.style.style;
    }
    set
    {
        this.style.style = value;
    }
}

а затем добавьте свойство:

public MyStyle Style
{
    get
    {
        return this.style;
    }
}

и измените строку:

protected string style;

в

protected readonly MyStyle style = new MyStyle();

Не забудьте в исходном HTML-элементе управления веб-пользователями, чтобы заменить this.Style на this.Styles.

ПРИМЕЧАНИЕ. У меня не было терпения, чтобы проверить код самостоятельно, поэтому он может не работать, поэтому вам придется исправить его самостоятельно. По крайней мере, вы поняли мою идею.

После исправления вы можете отредактировать мой ответ и заменить неправильный код на свой фиксированный код.

Буду очень благодарен!

Этот веб-пользовательский элемент управления представляет собой нужный вам ASP NumericUpDown!

Ответ 4

Если вы застряли на .NET 4.0 и хотите использовать собственный тип ввода "HTML5" (вместо NumericUpDown из Ajax Control Toolkit), вы можете использовать комбинацию элемента управления ASP TextBox с дополнительным тегом типа

<asp:TextBox runat="server" ID="txtMyTextBox" type="number" min="0" max="10" step="1"/>

Если вы хотите предотвратить ввод текста, вы даже можете добавить FilteredTextBoxExtender из Ajax Control Toolkit:

<ajaxToolkit:FilteredTextBoxExtender runat="server" TargetControlID="txtMyTextBox" FilterType="Numbers" />