Question

let's say I want to display my "Person" class.
I can do it in two ways:

  1. put a few asp:labels in my html, and fill them in my server code:

    lblName.Text = person1.Name 
    lblAge.Text = person1.Age 
    
  2. use the asp:formView control, so my server code will look like this:

    Dim myDataSource = New Object() {person1}
    FormView1.DataSource = myDataSource
    FormView1.DataBind()
    

    and my html will look like this:

    <asp:FormView ID="FormView1" runat="server">
        <ItemTemplate>
            Name:<%# Eval("Name")%>
            <br />
            Age:<%# Eval("Age")%>
        </ItemTemplate>
    </asp:FormView>
    

which way is better? what is the cost of using the server tags?

Was it helpful?

Solution

It is the same because the controls have to be runat="server" and it assign the values to the control from server side.

The main difference is that you assign the values in code_behind file or in markup file. Wherever you prefer. In both cases it will need to go server side to gather that values.

I don't think the cost of using server tags would be different to assign values in code file, because they are processed in page's render phase.

Extrated from msdn:

The default model for adding code to an ASP.NET Web page is to either create a code-behind class file (a code-behind page) or to write the page's code in a script block with the attribute runat="server" (a single-file page). The code you write typically interacts with controls on the page. For example, you can display information on the page from code by setting the Text (or other) properties of controls. Another possibility is to embed code directly into the page using an embedded code block. Embedded Code Blocks An embedded code block is server code that executes during the page's render phase. The code in the block can execute programming statements and call functions in the current page class.

Uses for Embedded Code Blocks Embedded code blocks are supported in ASP.NET Web pages primarily to preserve backward compatibility with older ASP technology. In general, using embedded code blocks for complex programming logic is not a best practice, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. In addition, because the code is executed only during the page's render phase, you have substantially less flexibility than with code-behind or script-block code in scoping your code to the appropriate stage of page processing. Some uses for embedded code blocks include: Setting the value of a control or markup element to a value returned by a function, as illustrated in the preceding example. Embedding a calculation directly into the markup or control property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top