次の方法で共有


How to use the ObjectDataSource as a DataSource, simple example

I thought I’d give an example on how to use the ObjectDataSource in a webpage.

A typical example could be listing states etc. This is fairly static data so it may be unnecessary to query a database for each request.

However, in this example we’ll use the Authors and their Books as an example.

This example will use and ObjectDataSource as a DataSource. The object will be returned by projecting Authors and Books into a new class via a LINQ query.

I use LINQ to Objects here but a database connection could be used as well.

So, let’s get down to it.

- Create a new WebSite, using Location: Filesystem works fine.

- Right click the added App_Code folder, Add New Item -> Class, name it BookShop.cs and replace the code with this.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

public class BookShop

{

    List<Author> Authors = new List<Author>();

    List<Book> Books = new List<Book>();

    public BookShop()

    {

        CreateBooksAndAuthors();

    }

    // This will return all Authors to be used by the dropdown.

    public List<Author> GetAuthors()

    {

        return Authors;

    }

    // Constructs a new list of BookAuthorItem for provided authorId and returns this to be used by the GridView.

    public List<BookAuthorItem> GetBooksByAuthorId(string authorId)

    {

        var q = from b in Books

     where b.AuthorId.Equals(authorId)

                select new BookAuthorItem

                {

                    BookId = b.BookId,

                    BookName = b.BookName,

                    AuthorName = Authors.First(x => x.AuthorId.Equals(authorId)).AuthorName,

                    AuthorAlias = Authors.First(x => x.AuthorId.Equals(authorId)).AuthorAlias

                };

        return q.ToList();

    }

    public class Author

    {

        public string AuthorId { get; set; }

        public string AuthorName { get; set; }

        public string AuthorAlias { get; set; }

    }

    public class Book

    {

        public string BookId { get; set; }

        public string BookName { get; set; }

        public string AuthorId { get; set; }

    }

    // We will project the query result into this class and return it to the calling client.

    public class BookAuthorItem

    {

        public string BookId { get; set; }

        public string BookName { get; set; }

        public string AuthorName { get; set; }

        public string AuthorAlias { get; set; }

    }

    private void CreateBooksAndAuthors()

    {

        // Create some books and authors.

        Authors.Add(new Author { AuthorId = "1", AuthorName = "Steve Stevenson", AuthorAlias = "The great Steve" });

        Authors.Add(new Author { AuthorId = "2", AuthorName = "Tom Tomson", AuthorAlias = "T.T." });

        Authors.Add(new Author { AuthorId = "3", AuthorName = "Eric Ericson", AuthorAlias = "The Swede" });

        Authors.Add(new Author { AuthorId = "4", AuthorName = "Paul Paulson" });

        Books.Add(new Book { BookId = "1", BookName = "The great book", AuthorId = "1" });

        Books.Add(new Book { BookId = "2", BookName = "Once upon a time", AuthorId = "1" });

        Books.Add(new Book { BookId = "3", BookName = "Learning is doing", AuthorId = "2" });

        Books.Add(new Book { BookId = "4", BookName = "The not so great book", AuthorId = "3" });

        Books.Add(new Book { BookId = "5", BookName = "Summer is good", AuthorId = "3" });

        Books.Add(new Book { BookId = "6", BookName = "Ah, you again!", AuthorId = "4" });

        Books.Add(new Book { BookId = "7", BookName = "Book about cats", AuthorId = "4" });

        Books.Add(new Book { BookId = "8", BookName = "My story", AuthorId = "4" });

    }

}

- Now on the Default.aspx page, drop a DropDownList from the toolbox onto it.

- Select "Choose Data Source...".

- Select "<New Data Source>" from the "Select a datasource" dropdown.

- Select Object in the "Choose a Data Source Type" dialog, and then OK.

- Select BookShop in the "Choose a Business" dialog, and then Next.

- Select "GetAuthors" from the "Choose a method" dropdown, and then Finish.

- Select AuthorName as the data field to display in the DropDownList, select AuthorId as the datafield for the value of the DropDownList, and OK.

- Select the "Enable AutoPostback" checkbox.

- Now on the Default.aspx page, drop a GridView from the toolbox (Data section) onto it.

- Select "<New Data Source>" from the "Choose Data Source..." list

- Select Object in the "Choose a Data Source Type" dialog, and then OK.

- Select BookShop in the "Choose a Business" dialog, and then Next.

- Select "GetBooksByAuthorId" from the "Choose a method" dropdown, and then Next.

- Select "Control" in the "Parameter Source" dropdown and "DropDownList1" as the ControlID in the "Define Parameters" dialog, and Finish.

- That is all, your Default.aspx page should now have the following in the body of the source.

<body>

    <form id="form1" runat="server">

   

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"

        DataSourceID="ObjectDataSource1" DataTextField="AuthorName" DataValueField="AuthorId">

    </asp:DropDownList>

    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"

        SelectMethod="GetAuthors" TypeName="BookShop">

    </asp:ObjectDataSource>

   

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource2">

        <Columns>

            <asp:BoundField DataField="BookId" HeaderText="BookId"

                SortExpression="BookId" />

            <asp:BoundField DataField="BookName" HeaderText="BookName"

                SortExpression="BookName" />

            <asp:BoundField DataField="AuthorName" HeaderText="AuthorName"

                SortExpression="AuthorName" />

            <asp:BoundField DataField="AuthorAlias" HeaderText="AuthorAlias"

                SortExpression="AuthorAlias" />

        </Columns>

    </asp:GridView>

   

    <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectMethod="GetBooksByAuthorId" TypeName="BookShop">

        <SelectParameters>

            <asp:ControlParameter ControlID="DropDownList1" Name="authorId" PropertyName="SelectedValue" Type="String" />

        </SelectParameters>

    </asp:ObjectDataSource>

    </form>

</body>

- Run the application, you should now be able to change the content of the GridView by selecting different authors with the DropDownList.

"ObjectDataSource Class"

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx

"Language-Integrated Query (LINQ) - Projection Operations"

https://msdn.microsoft.com/en-us/library/bb546168.aspx

Comments

  • Anonymous
    January 15, 2010
    great! Thanks!

  • Anonymous
    September 18, 2015
    Fantastic tutorial just what the doctor ordered. Thanks a heap or is that a stack? LOL!