0
我试图使用详细信息视图将项目插入数据库。我使用dropdownList来插入CategoryID列,因为它是一个外键,我不希望用户能够插入任何他们想要的数字。下拉列表获取来自Categories表中主键的值。出于某种原因,其他行正在插入,但categoryID在数据库中具有空值。我不知道我做错了什么,任何帮助将不胜感激。以下是设计页面中的一些代码。ASP.net的详细信息视图列未插入数据库
<asp:SqlDataSource ID="sqlDetailsViewDDl" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [Id] FROM [Categories]" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [Categories] WHERE [Id] = @original_Id" OldValuesParameterFormatString="original_{0}">
<DeleteParameters>
<asp:Parameter Name="original_Id" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" AutoGenerateRows="False" DataKeyNames="Id" DataSourceID="SqlDataSource1" Height="50px" OnItemDeleting="DetailsView1_ItemDeleting" Width="250px">
<Fields>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="sqlDetailsViewDDl" DataTextField="Id" DataValueField="Id" AutoPostBack="True"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CategoryLabel" Text='<%# Eval("CategoryID") %>' runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
如果你不知道,直接在您的视图定义你的数据库访问是绝对可怕的想法。如果你想做正确的事情,你应该为此创建一个存储库,以便应用程序的前端不知道数据来自何处或者连接字符串等细节,它只是暴露诸如GetCategories之类的方法。 –