views:

145

answers:

3

I know how to do this in MVC:

<title> <%= Model.Title %> </title>

I also know how to bind a SQLDataSource or ObjectDataSource to a control on a form or listview.

But how do I render a field from my SQLDataSource or ObjectDataSource directly into the HTML?

+1  A: 

You can declare a property and set its value using your desired field's value.

Code-behind:

private string myTitle;
protected string MyTitle
{
   get { return myTitle; }
   set { myTitle = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
    MyTitle = "Testing 123!";
}

Markup: <title><%= MyTitle %></title>

Ahmad Mageed
+2  A: 

You can use the Page.Title property to set the title in code behind.

Once you've run your SelectCommand or equivalent on your data source, just simply assign Page.Title a value from the result set.

Alternately, you can use the aspx page itself, and just inside the html assign a text string, like this:

<title>
  <%= dataSource.Select(...) %>
</title>
womp
Ah, missed the obvious! Admittedly Page.Title is the simplest approach in this case. My reply could be useful for other page elements or where a property's value is used in multiple places.
Ahmad Mageed
+1  A: 

In WebForms you still need to use a WebControl that implements DataBinding as the "container" for your fields. For instance, a GridView, Repeater, ListView, FormView or DetailsView. Unfortunately there isn't a WebControl designed specifically for rending just one row or object. So, you have a choice:

Use a Repeater something like this:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="MyDataSource">
  <ItemTemplate>
   <%# Eval("MyProperty") %>
  </ItemTemplate>
 </asp:Repeater>

Another alernative is to not use a DataSource. Instead, add properties to your page and then bind your data to these. For example, in your page codebehind:

public string MyPageProperty 
{
 get { return _myPageProperty; }
 set { _myPageProperty = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
 MyPageProperty = "This is some data";
}

You can then do this in your page:

<div>The value is: <%= MyPageProperty %></div>

Hope that helps.

Dan Diplo