【发布时间】:2015-09-04 05:15:50
【问题描述】:
我使用下面的代码首先从 category entity 检索 category Id 并将其绑定到 dropdownlist 即 DropDownlistCategory 。现在我想将 category ID 从下拉列表插入到包含四列的产品实体在数据库中如
ProductName,CategoryID,QuantityPerUnit and UnitPrice.
但是在插入下拉列表值时,它总是会从下拉列表中选择第一个值。
使用这个:
prod.CategoryID = Convert.ToInt32(DropDownListCategory.SelectedValue);
正确吗?
NewProduct.aspx 代码:-
<asp:DropDownList ID="DropDownListCategory" runat="server"CssClass="form- control" Width="100px" OnSelectedIndexChanged="DropDownListCategory_SelectedIndexChanged" >
</asp:DropDownList>
NewProduct.cs 代码:-
LaunderDBEntities context = new LaunderDBEntities();
protected void Page_Load(object sender, EventArgs e)
{
var categoryId = from cat in context.Categories
select new
{
categoryID = cat.CategoryID,
};
DropDownListCategory.DataSource = categoryId.ToList();
DropDownListCategory.DataValueField = "categoryID";
DropDownListCategory.DataTextField = "categoryID";
DropDownListCategory.DataBind();
}
protected void btnAddProduct_Click(object sender, EventArgs e)
{
SaveProductInfo();
}
private void SaveProductInfo()
{
Product prod = new Product();
prod.ProductName = txtProductName.Text;
prod.CategoryID = Convert.ToInt32(DropDownListCategory.SelectedValue);
prod.QuantityPerUnit = Convert.ToInt32(txtQuantity.Text);
prod.UnitPrice =Convert.ToInt32(txtUnitPrice.Text);
ProductDA prdDa = new ProductDA();
prdDa.InertProductDetails(prod);
Label5.Text = "<p style='color:Green;'>Information Successfully saved!</p>";
Response.Redirect("ProductInfo.aspx");
}
【问题讨论】:
标签: c# asp.net entity-framework