1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.