简体   繁体   中英

Two-way binding of string property to TextBox in ASP.NET WebForms

I am trying to implement the simplest possible (so it seemed to me) databinding of a TextBox to a property of the page, except the databinding is supposed to be two-way, so instead of <%# Test %> , I use <%# Bind("Test") %> . (Actually, the goal is to have a single object as a property and to bind to its properties, but let's start from something simple.) I am testing it on this simple code:

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();
        }
    }
}

The call of DataBind() results in an InvalidOperationException : Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

What is wrong with this approach?

Sadly, Eval and Bind can only be used in conjunction with a databound control such as a grid. This is because they expect to be executed within a naming container that has a current data item, such as the selected row in a grid.

So you can use that syntax to bind to a textbox that's located within a grid row template or suchlike , but not a textbox out on its own.

You should be using any one of

  1. Microsoft.Ajax library which has two way data binding support.
    1. Knockout Js (Mv* style, supports two way binding)
    2. Angular Js (MV* style, supports two way binding)

using above framework you can retrieve json object and bind that directly to any of html element or attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM