【问题标题】:Two-way binding of string property to TextBox in ASP.NET WebFormsASP.NET WebForms中字符串属性到TextBox的双向绑定
【发布时间】:2014-10-21 11:39:42
【问题描述】:

我正在尝试实现 TextBox 到页面属性的最简单的可能(在我看来)数据绑定,除了数据绑定应该是双向的,所以我使用 @ 而不是 <%# Test %> 987654322@。 (实际上,目标是将单个对象作为属性并绑定到它的属性,但让我们从简单的事情开始。)我正在用这个简单的代码对其进行测试:

TestForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TestTextBox" runat="server" Text='<%# Bind("Test") %>' />
    </div>
    </form>
</body>
</html>

TestForm.aspx.cs:

using System;

namespace WebApplication1
{
    public partial class TestForm : System.Web.UI.Page
    {
        public string Test { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Test = "Hello";
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            DataBind();
        }
    }
}

DataBind() 的调用导致InvalidOperationExceptionEval()、XPath() 和 Bind() 等数据绑定方法只能在数据绑定控件的上下文中使用。

这种方法有什么问题?

【问题讨论】:

    标签: c# asp.net .net data-binding webforms


    【解决方案1】:

    遗憾的是,EvalBind 只能与数据绑定控件(如网格)结合使用。这是因为它们希望在具有当前数据项的命名容器中执行,例如网格中的选定行。

    因此,您可以使用该语法绑定到 located within a grid row template or suchlike 的文本框,但不能单独绑定到文本框。

    【讨论】:

      【解决方案2】:

      你应该使用任何一种

      1. Microsoft.Ajax 库具有两种数据绑定支持。
        1. Knockout Js(Mv*风格,支持双向绑定)
        2. Angular Js(MV*风格,支持双向绑定)

      使用上述框架,您可以检索 json 对象并将其直接绑定到任何 html 元素或属性。

      【讨论】:

        猜你喜欢
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        • 2017-05-17
        • 1970-01-01
        • 2012-06-20
        相关资源
        最近更新 更多