【问题标题】:Is there a way to reference a asp ID using a variable in code behind有没有办法使用后面代码中的变量来引用 asp ID
【发布时间】:2019-03-24 20:49:10
【问题描述】:

我正在尝试使用 c# 变量来删除属性。

在实际编码应用程序之前,我正在测试我的方法。

我已经尝试过 javascript 和 jQuery,但没有发现任何允许 用代码隐藏中的字符串值替换 TextBox ID。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="myText" runat="server" required="required"></asp:TextBox>

    </div>
    </form>

</body>

</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class index : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string straspID = "myText";


            bool fieldRequired = false;

            if (fieldRequired == false)
            {

                //FindControl("myText");
                FindControl(straspID);
                if (straspID != null)
           //         
                myText.Attributes.Remove("required");
          // I want to use straspID instead of the ID of the asp page
          // which will returned from a table - I'm simulating here
          // I get an error if I use straspID for remove attribute 
            }


        }

    }
}

我的预期结果是删除所选 ID 的属性。 我目前遇到语法错误。

【问题讨论】:

  • 您是否尝试过使用myText?为什么要改用字符串?
  • 我将从包含 asp ID 的表中获取值
  • mytext 有效,但我不知道标签在现实世界中的价值
  • 我的建议是不要使用 Web 表单......它实际上没有用,并且在这一点上被认为是遗留......使用.net core mvc 或 web api。无论如何,看看stackoverflow.com/a/34759219/8167494,它可能会有所帮助
  • 将其称为无用有点牵强@IsaacVidrine。

标签: javascript c# jquery asp.net


【解决方案1】:

这个

            FindControl(straspID);

没有按照你的想法去做。

您能否检查您的 index.aspx.designer.cs 文件,看看是否有一个名为“myText”的受保护成员变量?

如果有,您可以这样做:-

        if (fieldRequired == false)
        {
            myText.Attributes.Remove("required");
        }

如果没有名为 myText 的受保护成员,则在类级别添加一个到“索引”:-

namespace WebApplication2
{
    public partial class index : System.Web.UI.Page 
    {
        protected Textbox myText;

        (etc)

只要您声明它的类型正确且名称和大小写相同,就无需求助于 FindControl 来访问服务器控件。

【讨论】:

  • 看过了。是的 。我必须找到一种使用该变量的方法,因为这些值将来自从 sql 表创建的列表。结构会有帮助吗?
【解决方案2】:

private void loadform(List providerList) { foreach(providerList 中的 ProviderInRequest 请求) { // 计划的标记 div 控件 ctrl = FindControl("div" + req.aspName); // 如果我们找到它,则将其设置为 true。 如果 (ctrl != null) { //设置div可见 ctrl.Visible = true;

                // set label to proper text
                Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
                lbl.Text = displayName;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 2019-09-03
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多