简体   繁体   English

从代码隐藏 c# 中的输入 html 中获取值

[英]Get value from input html in codebehind c#

I did some research and found out how I can read a value from the input html textbox.我做了一些研究,发现了如何从输入的 html 文本框中读取值。

This worked fine for me, but at once it doesn't work.这对我来说很好用,但立刻就行不通了。

This is my code, it input html returns null这是我的代码,它输入 html 返回 null

<input type="text" name="inpNickname" placeholder="Nickname" data-placement="right" data-toggle="tooltip" title="Nickname" id="txtNickname" runat="server"/>

<input type="text" name="inpPassword" placeholder="Password" data-placement="right" data-toggle="tooltip" title="Password" id="txtPassword" runat="server"/>

string Nickname = Request.Form["inpNickname"];
string Password = Request.Form["inpPassword"];

If I change the Request.Form[] to the ID's, it still doesn't work.如果我将 Request.Form[] 更改为 ID,它仍然不起作用。

Since it is running at the server...由于它在服务器上运行...

txtNickname.Value and txtPassword.Value will give you what you need. txtNickname.ValuetxtPassword.Value会给你你需要的。

When you specify runat="server" you are essentially giving a property to your codebehind class.当您指定runat="server"您实际上是在为您的代码隐藏类提供一个属性。 So you can access that property and it's properties directly.因此,您可以直接访问该属性及其属性。

Why not use a server control ?为什么不使用服务器控件

<asp:TextBox ID="txtNickname" runat="server" />

Code behind:后面的代码:

var nickName = txtNickname.Text;
string Nickname = txtNickname.Text;
string Password = txtPassword.Text;

They're running on the server, see this他们在服务器上运行,看到这个

使用name="inpNickname"不起作用,在这种情况下只能使用 ID: txtNickname

The standard approach:标准方法:

Frontend :前端:

 <asp:TextBox runat="server" id="testid"></asp:TextBox>

Backend :后端:

String test = testid.text;

Usually i use these simple server controls, but with complicated forms, and post backs, things are not always so simple... I've found another surefire way to get the clients control from the back end, even when the control is not found in the code-behind by using thecontrol.text or thecontrol.value for example :通常我使用这些简单的服务器控件,但是对于复杂的表单和回发,事情并不总是那么简单......我找到了另一种从后端获得客户端控制的可靠方法,即使没有找到控件在代码隐藏中使用 thecontrol.text 或 thecontrol.value 例如:

Backend :后端:

String test = Request.Form["ctl00$MainContent$TextboxControlsId"].ToString();

This will fetch the contents of the textbox with id: TextboxControlsId, which is defined outside of sitemaster.这将获取 ID 为 TextboxControlsId 的文本框的内容,它是在站点管理员之外定义的。

If you need to find the ID of your control (most likely it wont conserve the same id you wrote in the front end), you can loop through your form control keys by using :如果您需要查找控件的 ID(很可能它不会保留您在前端编写的相同 ID),您可以使用以下命令循环遍历表单控件键:

foreach (string s in Request.Form.Keys ) { 
    Response.Write(s.ToString() + ":" + Request.Form[s] + ""); 
} 

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

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