HTML5 Types in ASP.NET

2019-08-09 01:32发布

问题:

Site will exclusively be used on mobile devices. So for fields requiring only numeric input, I want to bring up the numeric keypad. I can successfully do this by using an html input element with the type set to tel. I want to add an asp:RequiredFieldValidator to this field and based on MSDN.

I need to set the input to runat="server". When I do this, I get this error;

tel is not a valid type for an input tag.

If I remove the runat="server", I get

Unable to find control id Contract referenced by the ControlToValidate property of ''

Here is my code:

<input type="tel" runat="server" id="Contract"></input>
<asp:RequiredFieldValidator runat="server" ControlToValidate="Contract" 
                            ValidationGroup="IfOnRent" Text="*" 
                            ErrorMessage="Contract Required">
</asp:RequiredFieldValidator>

Am I just out of luck and have to code my own validations?

回答1:

You may want to leave "type" undeclared in your code "front". You can set this in the code behind (maybe in the Page_Init or Page_Load):

this.Contract.Attributes.Add("type", "tel");


回答2:

If you have Microsoft .NET Framework 4 Reliability Update 1 (KB2533523) installed, than TextBox accepts new html5 input types (you would need it for UpdatePanel to recognize them on postback too).

Or you can just inherit HtmlInputText in your own control (any .net version - any input type):

[ToolboxData("<{0}:Input runat='server' />"), Themeable(true)]
public sealed class Input: HtmlInputText { }


回答3:

If you are using C#

Contract.Attributes["type"]="tel"

Writing inline types for html inputs may produce parse error in .net. So add the above line of code in your PageLoad()



回答4:

you can use Make sure that the submit button has the same validationgroup property value as the requiredfieldvalidator