Search code examples
asp.nettemplatesfieldasp.net-dynamic-data

In asp.net dynamic data, how to use UIHint to create a auto-fill field?


I'm using asp.net dynamic data. There is a field I want to auto fill for users. The file is user name which can be obtained with integrated windows authentication.

I created a Field Template and it works in Insert mode, but in Update mode, once another user updates the record, the new user name should be saved, but it didn't.


Solution

  • I found a solution and I want to share it.

    Apply UIHint for the entity field:

    [UIHint("UserName")]
    public object Name { get; set; }
    

    Create a a new FieldTemplate:

    <asp:TextBox ID="TextBox1" runat="server" ReadOnly="true" BorderStyle="None"
    BackColor="Transparent" Text='<%# FieldValueEditString %>'></asp:TextBox>
    

    Code behind for FieldTemplate:

    public partial class UserName_EditField : FieldTemplateUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SetUpValidator(RequiredFieldValidator1);    
            EditFieldTemplateUserControl.InsertHelpText(this);
        }
    
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
    
            TextBox1.Visible = true;
        }
    
        protected string UserName
        {
            get
            {
                var name = this.Page.User.Identity.Name.ToString();
                return name;
            }
        }
    
        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            if (Page.IsPostBack)
            {// only assign value when user posts back.
                this.TextBox1.Text = this.UserName.ToUpper();
                dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
            }
        }
    
        public override Control DataControl
        {
            get
            {
                return TextBox1;
            }
        }
    }