C# 如何使用asp.net实体数据模型将选定的dropdownlist值插入数据库
我使用下面的代码首先从C# 如何使用asp.net实体数据模型将选定的dropdownlist值插入数据库,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,我使用下面的代码首先从category entity检索category Id,并将其绑定到dropdownlist,即DropDownlistCategory。现在我想将该category Id从dropdownlist插入数据库中包含四列的产品实体,例如 ProductName,CategoryID,QuantityPerUnit and UnitPrice. 但在插入dropdownlist值时,它将始终从dropdownlist中选择第一个值 使用此选项: prod.CategoryI
category entity
检索category Id
,并将其绑定到dropdownlist
,即DropDownlistCategory
。现在我想将该category Id
从dropdownlist插入数据库中包含四列的产品实体,例如
ProductName,CategoryID,QuantityPerUnit and UnitPrice.
但在插入dropdownlist值时,它将始终从dropdownlist中选择第一个值
使用此选项:
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");
}
LaunderDBEntities上下文=新的LaunderDBEntities();
受保护的无效页面加载(对象发送方、事件参数e)
{
var categoryId=来自context.Categories中的cat
选择新的
{
categoryID=cat.categoryID,
};
DropDownListCategory.DataSource=categoryId.ToList();
DropDownListCategory.DataValueField=“categoryID”;
DropDownListCategory.DataTextField=“categoryID”;
DropDownListCategory.DataBind();
}
受保护的无效btnAddProduct\单击(对象发送者,事件参数e)
{
SaveProductInfo();
}
私有void SaveProductInfo()
{
产品生产=新产品();
prod.ProductName=txtProductName.Text;
prod.CategoryID=Convert.ToInt32(DropDownListCategory.SelectedValue);
prod.QuantityPerUnit=Convert.ToInt32(txtQuantity.Text);
prod.UnitPrice=Convert.ToInt32(txtUnitPrice.Text);
ProductDA prdDa=新ProductDA();
prdDa.产品详细信息(产品);
Label5.Text=“