c# - 如何使用 asp.net 实体数据模型将选定的下拉列表值插入数据库

标签 c# asp.net entity-framework

我使用下面的代码首先从 category entity 中检索 category Id 并将其绑定(bind)到 dropdownlistDropDownlistCategory 。现在我想将 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");

    }

最佳答案

使用 IsPostBack 在页面加载中。仅在第一次加载页面时绑定(bind)下拉列表。

 protected void Page_Load(object sender, EventArgs e)
 {
        if(!IsPostBack)
        { 
             //.... code to bind the dropdownlist

        }
}

关于c# - 如何使用 asp.net 实体数据模型将选定的下拉列表值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390577/

相关文章:

c# - 未找到 VisualStateGroups?

c# - 从同一对象处置对象

.net - 有 Postsharp 生产经验的人吗?

mysql - 带有 Entity Framework 的空间 MySQL

c# - 处理我的 ObjectContext 的正确方法是什么?

c# - 手动附加后 EF 解析导航属性

c# - Dapper 查询结果在对象中将表的 Pk 设置为 null

c# - EF6 ToListAsync 不运行异步但阻塞线程

javascript - Kendo UI 图表 - OnClick 事件

asp.net mvc 调试器抛出 SEHException