asp.net - 绑定(bind)TextBox时如何调用方法

标签 asp.net

我想在 EditItemTemplate 中绑定(bind)()一个 TextBox,但我需要在显示之前将文本框的原始值传递给一个函数。我的目标是在显示值之前对其进行格式化。这是一个复杂的格式化规则,所以我不能使用任何内置的格式化程序。使用 Eval() 很容易做到,但使用 Bind() 就另当别论了。我知道它可以使用代码隐藏中的事件来完成,但我试图从 aspx 页面完成这一切。

例子:

<EditItemTemplate>
        <asp:TextBox ID="NameTextBox" Text=<%# Bind("Name") %> MaxLength="255" runat="server" />
</EditItemTemplate>

谢谢...

最佳答案

您不能从标记中执行此操作。 ASP.NET 有一个特殊情况的代码来解析 Bind语法并为其生成特殊代码。这就是为什么双向数据绑定(bind)不支持 Bind() 以外的任何内容。 .您可以在 How ASP.NET databinding deals with Eval() and Bind() statements 中找到更多信息。 Eilon Lipton 的文章:

To the surprise of many readers, there isn’t a bind method in ASP.NET! When ASP.NET parses your file and sees you're using a databinding expression (in the angle-bracket-percent-pound format, "<%# %>") it has special-case code to parse for the Bind syntax and generates some special code for it. When you use <%# Bind("Name") %> it's not a real function call. If ASP.NET parses the code and detects a Bind() statement, it splits the statement into two parts. The first part is the one-way databinding portion, which ends up being just a regular Eval() call. The second part is the reverse portion, which is typically some code along the lines of "string name = TextBox1.Text" that grabs the value back out from where it was bound.

Non-Bind() databinding statements are literal code (we use CodeSnippetExpressions in CodeDom), so arbitrary code in the language of your choice is allowed. However, because ASP.NET has to parse Bind() statements, two-way databinding doesn’t support anything other than Bind(). For example, the following syntax is invalid because it tries to invoke arbitrary code and use Bind() at the same time: <%# FormatNameHelper(Bind("Name")) %> The only formats supported in two-way databinding are Bind("field") and Bind("field", "format string {0}").



因此,请考虑在代码隐藏中执行此操作,或使用 Eval代替方法。

关于asp.net - 绑定(bind)TextBox时如何调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10079622/

相关文章:

asp.net - 将 Web 应用程序部署到 Azure 但仍显示 Microsoft 页面

c# - 将相同数据绑定(bind)到多个下拉列表

Jquery/Bootstrap DataTable 排序无法正常工作

asp.net - 尝试从 web.config 打开一个部分会出现 ConfigurationErrorsException : The entry KEY has already been added

c# - 从 Dropbox 下载文件 C#

java - session cookie 和持久性 cookie

mysql - 单击按钮即可运行两个或多个查询

asp.net - Kestrel 对于在 ALB 后面的 AWS ECS 上运行的 ASP.NET Core 网站是否足够?

c# - 防止 Automapper 将 IEnumerable 属性转换为列表

asp.net - 在 WCF 服务中使用 ASP.NET 成员资格提供程序身份验证