简体   繁体   English

通过在文本字段上按Enter在用户控件上提交表单不起作用

[英]Submitting a form on a user control by pressing enter on a text field does not work

This seems to be a common problem but I cannot find a solution. 这似乎是一个普遍的问题,但我找不到解决方案。

I type in my username and password which are in a login control I have created. 我输入我创建的登录控件中的用户名和密码。 I then press enter once I've typed in my password and the page just refreshes. 输入密码后,然后按Enter键,页面将刷新。 It triggers the page load event but not the button on click event. 它触发页面加载事件,但不触发点击事件按钮。

If I press the submit button then everything works fine. 如果我按下提交按钮,则一切正常。

using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML. 使用表单的默认按钮是正确的,但是您需要提供正确的ID,因为它将呈现为HTML。

so you do as Jon said above: 所以您要按照乔恩在上面说的做:

<form runat="server" DefaultButton="SubmitButton">

But ensure you use the Button name that will be rendered. 但是,请确保使用将要呈现的Button名称。 You can achieve this my making the Button public in your control, or a method that will return it's ClientId. 您可以通过在控件中公开Button或将其返回为ClientId的方法来实现。

Let's say your button is called btnSubmit, and your implementation of your control ucLogin. 假设您的按钮称为btnSubmit,而您的控件ucLogin的实现。

Give your form an id 输入您的表格ID

<form runat="server" id="form1">

Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id. 然后,在页面中,将代码加载到页面的后面,然后将按钮客户端ID设置为DefaultButton。

protected void Page_Load(object sender, EventArgs e)
{
   form1.DefaultButton = ucLogin.btnSubmit.ClientID;
}

如果使用的是ASP.NET 2.0或更高版本,则可以为页面的Form设置默认按钮属性:

<form runat="server" DefaultButton="SubmitButton">

Pressing ENTER on a text input executes Form.onsubmit , not Button.onclick . 在文本输入上按ENTER键将执行Form.onsubmit ,而不是Button.onclick

I suppose this was inspired by the fact that you can have a form without an actual submit button (depending solely on the use of ENTER). 我想这是受以下事实启发的:您可以拥有一个没有实际提交按钮的表单(仅取决于ENTER的使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM