使用 ASP.Net,如何使用服务器端代码写入客户端控件(文本框)?
如果我有一个标准的 HTML 文本框:我可以使用 Request.Form 检索该值。
但是我该如何从服务器端填充这个文本框呢?我尝试过
Request.Form["txtTest"] = "blah";
,但收到只读错误。
If I have a standard HTML textbox: I can retrieve the value using Request.Form.
But how do I go about populating this textbox from the server-side? I tried
Request.Form["txtTest"] = "blah";
but got a readonly error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望在服务器端通过其 id 访问控件(按照 .net 控件)获得一流的支持,您需要使其具有 runat="server" 标记。
否则,您可以通过在后面的代码中设置一个属性并使用数据绑定在 aspx 页面上从中提取值来动态设置该值,
例如
If you want to have first class support for accessing the control by its id on the server side (as per .net controls) you would need to make it so it has a runat="server" tag.
Otherwise you can set the value dynamicaly by having a property in your code behind and pulling in the value from this on the aspx page using databinding e.g.
and
请记住,当您的服务器代码运行时,客户端文本框不存在。托管该控件的 html 页面已作为新请求提交到服务器,并且 Web 浏览器期望您响应一个全新的页面。在响应到达之前,浏览器将保持页面显示,但这只是一个方便的 shell。保存文本框的 DOM 已经消失,并且您还没有创建新的 DOM。您无法通过更新请求中的属性来直接更改您的响应。
这意味着您需要使用控件的服务器端表示。如果它是服务器控件,您可以尝试 txtTest.Text = "blah"; 否则,您需要找到生成输入标记的位置并进行适当的更改。
Remember that at the point when your server code runs, the client side textbox doesn't exist. The html page hosting the control was already submitted to the server as new request, and the web browser is expecting you to respond with a completely new page. Until that response arrives the browser will leave the page displayed, but that's just a convenient shell. The DOM that held your textbox is gone, and you haven't created a new one yet. You can't directly change your response by updating a property in the request.
This means you need to use the server-side representation of the control. If it's a server control, you might try
txtTest.Text = "blah";
Otherwise, you need to the find where you generate that input tag and alter things appropriately.