代码之家  ›  专栏  ›  技术社区  ›  baptiste

绑定标签与代码隐藏集,最佳实践

  •  3
  • baptiste  · 技术社区  · 17 年前

    我想知道在asp.net中使用bind标记和为控件设置direct属性之间的最佳实践是什么。


    在后台

    public string Description {get; set;}
    

    <asp:Literal ID="txtDescription" runat="server" Text='<%# Description %>' />
    

    在后台

    public string Description
    {
        get { return txtDescription.Text ; }
        set { txtDescription.Text = value; }
    }
    

    <asp:Literal ID="txtDescription" runat="server" />
    

    第一个是最好将设计与代码分开,这样就可以在不破坏代码的情况下自由地更改ID。但似乎我们有时可以得到很长的绑定标记,就像下面这个很短的示例:

    Text='<%# ((fn_SearchReminders)Container.DataItem).dtDateActivation.Value.ToString("yyyy-MM-dd - hh:mm") %>'
    
    2 回复  |  直到 17 年前
        1
  •  3
  •   Chris Marisic    17 年前

    唯一值得使用绑定表达式的时间是。。。数据绑定。对于处理文本框之类的静态控件,最好的访问方式是第二种情况下的访问方式。

    string iSomeView.Description
    {
        get { return txtDescription.Text ; }
        set { txtDescription.Text = value; }
    }
    

    使用类似于此的方法还可以轻松构造复杂对象:

    Person iSomeView.Person
    {
        get { return new Person { Name = txtName.Text, Phone = txtPhone.Text }; }
        set { txtName = value.Name; txtPhone.Text = value.Phone; }
    }
    
        2
  •  0
  •   Hemanshu Bhojak    17 年前

    如果您正在使用GridView或Repeater之类的控件,您只需使用 并可以选择指定格式字符串,如 “/>

    在直接包含在页面中的其他控件的情况下,您可以考虑使用私有方法,只要您觉得合适,就可以设置它们的属性。

    private void SetFormFields(Employee emp){
         lblName.Text = emp.Name;
         txtDateOfBirth.Text = emp.BirthDate.ToShortDateString();
    }
    

    并在页面加载事件中或从其他位置调用它。