ASP.NET
Associazione dati
Ricerca…
Origine dati SQL
I controlli che possono essere associati ai dati possono utilizzare i controlli SqlDataSource
. Il controllo SqlDataSource
consente non solo di recuperare i dati da un database, ma anche di modificare e ordinare i dati.
Recupero dati
Procedura memorizzata:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="sp_GetEmployees"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
Query SQL:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT
EmployeeID,
EmployeeFirstName,
EmployeeLastName
FROM
dbo.Employees">
</asp:SqlDataSource>
parametri:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT
EmployeeID,
EmployeeFirstName,
EmployeeLastName
FROM
dbo.Employees
WHERE
DepartmentID = @DepartmentID;">
<SelectParameters>
<asp:ControlParameter ControlID="ddlDepartment"
Name="DepartmentID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
Essere consapevoli dell'opzione CancelSelectOnNullParameter
, che se impostato su true (predefinito) interromperà l'associazione dati se qualsiasi parametro è NULL
Uso di base
Vista a griglia:
<asp:GridView ID="GridViewEmployees"
runat="server"
AutoGenerateColumns="false"
DataSourceID="SqlDataSourceEmployees">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
<asp:BoundField DataField="EmployeeFirstName" HeaderText="First Name" />
<asp:BoundField DataField="EmployeeLastName" HeaderText="Last Name" />
</Columns>
</asp:GridView>
Oggetto origine dati
<asp:ObjectDataSource ID="ObjectDataSourceEmployees" runat="server"
TypeName="MyPackage.MyDataAccessClass"
DataObjectTypeName="MyPackage.Employee"
SelectMethod="GetEmployees"
UpdateMethod="SaveEmployee"
InsertMethod="SaveEmployee">
</asp:ObjectDataSource>
Nel codice sottostante
La classe di accesso ai dati
public class MyDataAccess
{
public static List<Employee> GetEmployees()
{
List<Employee> results = new List<Employee>()
{
new Employee(){ Id=1, Name="John Smith" },
new Employee(){ Id=2, Name="Mary Jane" }
};
return results;
}
public static void SaveEmployee(Employee e)
{
// Persist Employee e to the DB/cache etc. here
}
}
La classe dei dipendenti
public class Employee
{
public Int32EmployeeId { get; set; }
public string Name { get; set; }
}
Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow