问题
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:
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>
回答2:
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>
回答3:
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.
来源:https://stackoverflow.com/questions/1150520/how-do-i-bind-a-database-field-to-an-html-title-element-in-asp-net-2-0