ASP.NET - 将 C# 变量传递给 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9826699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:47:29  来源:igfitidea点击:

ASP.NET - Passing a C# variable to HTML

c#asp.net

提问by Matthew

I am trying to pass variables declared in C# to html. The variables have all been declared as public in the code-behind.

我试图将在 C# 中声明的变量传递给 html。这些变量都在代码隐藏中声明为 public。

This is the HTML code I am using:

这是我正在使用的 HTML 代码:

<asp:TextBox ID="TextBoxChildID" Text='<%= Child_ID %>' runat="server" Enabled="false"></asp:TextBox>

The problem is that when the page loads, the text '<%= Child_ID %>' appears in the textbox instead of the value in the variable.

问题是当页面加载时,文本 '<%= Child_ID %>' 出现在文本框中,而不是变量中的值。

What is wrong please?

请问有什么问题?

采纳答案by David

All of this is assuming that this is just a textbox somewhere on your page, rather than in a DataBound control. If the textbox is part of an itemTemplate in a repeater, and Child_ID is something that differes by data row, then all of this is incorrect.

所有这些都假设这只是页面上某处的文本框,而不是 DataBound 控件中的文本框。如果文本框是转发器中 itemTemplate 的一部分,并且 Child_ID 是因数据行而不同的东西,那么所有这些都是不正确的。

Do this instead:

改为这样做:

<asp:TextBox ID="TextBoxChildID"  runat="server" Enabled="false"><%= Child_ID %></asp:TextBox>

In short, you're making the same mistake I was making when I asked this question: Why <%= %> works in one situation but not in another

简而言之,当我问这个问题时,您犯了同样的错误:为什么 <%= %> 在一种情况下有效,但在另一种情况下无效



Alternatively, in code-behind, you can have this in your ASPX:

或者,在代码隐藏中,您可以在 ASPX 中使用它:

<asp:TextBox ID="TextBoxChildID"  runat="server" Enabled="false"></asp:TextBox>

and this in your Code-Behind:

这在您的代码隐藏中:

TextBoxChildID.Text = Child_ID;

回答by Rafael Carvalho

The variable must be public first. And:

变量必须首先是公共的。和:

'<%# Child_ID %>' 

回答by Pankaj

<script type="text/javascript">
    function abc()
    {
        var id = document.getElementById('txtTextBox');
        id.value=<%=MyProperty %>;
        alert(id.value);
    }
</script>


protected int MyProperty
{
    get
    {
        return 1;
    }
}


Page.RegisterStartupScript(Guid.NewGuid().ToString(), 
 "<script language = 'javascript'>abc();</script>");

回答by Rafael Carvalho

In the HTML:

在 HTML 中:

<asp:HiddenField ID="HiddenField1" runat="server" />

In The Codebehind:

在代码隐藏中:

protected void Page_Load(object sender, EventArgs e)
{
    HiddenField1.Value = Child_ID;
}

It would be the best way, it creates a hidden input with the value.

这将是最好的方法,它创建一个带有值的隐藏输入。