tags:

views:

240

answers:

2

I would like to know what is the best practice between using bind tag and setting direct property to a control in asp.net.


aspx.cs

public string Description {get; set;}

aspx

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


aspx.cs

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

aspx

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


The first being best to separate design from code giving the liberty of changing even ID without breaking code. But it seems we can get very long bind tag sometime like this really short example:

Text='<%# ((fn_SearchReminders)Container.DataItem).dtDateActivation.Value.ToString("yyyy-MM-dd - hh:mm") %>'
+3  A: 

The only time it's worth using the binding expressions is when... databinding. For dealing with static controls like your textbox the best way to access it is the way you did in the second case.

This is even the case for dealing with the Model View Presenter implementation where generally your aspx page will inherent from iSomeView and you will access properties similar to

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

Using a method similar to this also allows you to construct complex objects easily:

Person iSomeView.Person
{
    get { return new Person { Name = txtName.Text, Phone = txtPhone.Text }; }
    set { txtName = value.Name; txtPhone.Text = value.Phone; }
}
Chris Marisic
Nice example. I agree, databinding is the only exception, otherwise it won't be long before you have logic in your view.
Chuck Conway
But you could put the logic into the public property as seen in my fist exemple. Just switch the auto-property to classic property with logic and bind in the aspx file.
lucian.jp
Lucian, I believe he meant that logic would start appearing in the .aspx file instead of the code file. Which is an antipattern in WebForms. In MVC it's fine if you completely get rid of the codebehind file.With my way, I tend to like to do input scrubbing like Trim() or regex replaces in the get.
Chris Marisic
A: 

If you are using controls like GridView or Repeater and the likes you can simply use ' /> and optionally specify the format string like ' /> where "d" stands for short date string.

In case of other controls which are directly contained in the page you can consider using a private method which will set their properties whenever you feel appropriate.

Like

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

and call it in the page load event or from some other place.

Hemanshu Bhojak