Gary O. Stenstrom
Gary O. Stenstrom

Reputation: 2294

Manually Binding a Model to an ASP.NET FormView using model binding

I am trying to load the details of a single product from a list of products displayed in a ListView into a FormView control using ASP.NET 4.5's model binding capability.

This is all hosted in a single ASPX page which decides which to display using a Multiview control. In one view I have the ListView which displays all the products. In another view I have the FormView control to display/edit the details of a single product. When I click on a single product record in the ListView, I want to display the view that contains the FormView, and load that product into the FormView for editing or review.

Following direction for Model binding in WebForms, I have defined the "SelectMethod" property of the FormView with a method that takes a ProductId as it's parameter. This method returns a single corresponding Product object. It is my understanding that somewhere in the lifecycle of the page this method is called and the FormView is automatically loaded.

Now, when I click on a record in the ListView to view its details, it fires the ItemCommand event handler. The event handler uses the Product Id from the selected record and retrieves the Product that corresponds to this Id.

The problem comes in that I then need to bind that Product to the FormView. How do I manually assign the Product as the model that the FormView binds to? When I attempt to manually set the DataSource of the FormView I get the error:

"DataSource or DataSourceID cannot be defined on 'ProductForm' when it uses model binding."

Has anyone else has this similar issue and figured out how to handle it?

Thanks,

G

Upvotes: 1

Views: 6498

Answers (1)

graham mendick
graham mendick

Reputation: 1839

There's no need to manually assign the Product because data binding takes care of this leg work for you.

Firstly, make sure you have some sort of Button in each row of the ListView with a CommandName of Select:

<asp:ListView ID="ProductList" runat="server" DataKeyNames="Id" ItemType="Product" SelectMethod="GetProductList">
<ItemTemplate>
    <%# Item.Name %>
    <asp:Button ID="SelectButton" runat="server" CommandName="Select" />
</ItemTemplate>
</asp:ListView>

Secondly, for the SelectMethod of the FormView make sure the product id parameter has the Control attribute specified where the string passed to the constructor must match the id of the ListView Control:

public Product GetProduct([Control("ProductList")] int? id)
{
    if (id.HasValue)
    {
        return GetProductList().First(p => p.Id == id.Value);
    }
    return null;
}

That's all you need to do, because when the Select button is clicked the SelectedValue of the ListView changes and the GetProduct method is automatically called and the FormView updated.

Upvotes: 2

Related Questions