如何从后面的 ASP.NET 代码访问 HTML 表单输入 [英] How to access HTML form input from ASP.NET code behind

查看:25
本文介绍了如何从后面的 ASP.NET 代码访问 HTML 表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的 HTML 表单,它根据数据库中存在的记录数插入到服务器端 div 标记中.这个 HTML 表单很好,一切看起来都很好.但是在我的操作页面上,我似乎无法从后面的代码访问输入元素.我曾尝试使用 Request 范围,但我对这种方法一无所知.还有其他建议吗?

以下所有建议都很棒,通常我会这样做.但是这些表单是在页面编译后即时构建的,所以 runat='server' 没有为我做任何事情.它只是将其传递给 HTML 页面.

解决方案

如果您正在访问纯 HTML 表单,则必须通过提交按钮(或通过 JavaScript 帖子)将其提交到服务器.这通常意味着您的表单定义将如下所示(我的内存不足 - 确保您检查 HTML 元素是否正确):

您应该能够像这样访问 customerName 和 customerPhone 数据:

string n = String.Format({0}", Request.Form[customerName"]);

如果您在表单中有 method="GET"(不推荐 - 它会弄乱您的 URL 空间),您将不得不像这样访问表单数据:

string n = String.Format({0}", Request.QueryString[customerName"]);

这当然只有在表单被发布"、提交"或通过回发"完成时才有效(即,有人点击了保存"按钮,或者这是通过 JavaScript 以编程方式完成的).

另外,请记住,只有在您不使用服务器控件(即 runat="server")时才能以这种方式访问​​这些元素.对于服务器控件,id 和 name 是不同的.

I have a basic HTML form that gets inserted into a server side div tag based on how many records exist in the database. This HTML form comes out just fine, and everything looks good. But on my action page I cannot seem to access the input elements from the code behind. I have tried using the Request scope, but I have come up empty on that approach. Any other suggestions?

All of the below suggestions are great, and normally that is what I would do. But these forms are being built on the fly after the page is being compiled, so runat='server' did not do anything for me. It just passed that along to the HTML page.

解决方案

If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via JavaScript post). This usually means that your form definition will look like this (I'm going off of memory - make sure you check the HTML elements are correct):

<form method="POST" action="page.aspx">

    <input id="customerName" name="customerName" type="Text" />
    <input id="customerPhone" name="customerPhone" type="Text" />
    <input value="Save" type="Submit" />

</form>

You should be able to access the customerName and customerPhone data like this:

string n = String.Format("{0}", Request.Form["customerName"]);

If you have method="GET" in the form (not recommended - it messes up your URL space), you will have to access the form data like this:

string n = String.Format("{0}", Request.QueryString["customerName"]);

This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback' (i.e., somebody clicked the 'Save' button, or this was done programmatically via JavaScript).

Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e., runat="server"). With server controls, the id and name are different.

这篇关于如何从后面的 ASP.NET 代码访问 HTML 表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆