3层C# asp.net:插入下拉列表选定的文本和值

3

I have a 3 Layer asp.net c# code. My BL:

    public DataTable ddl()
    {
        base.Link();
        string Query = "SELECT [nam], [idZone] FROM [zones] ORDER BY idZone";
        DataTable Output_Q = base.SelectDataText(Query);
        base.UnLink();
        return Output_Q;
    }
    public void insert()
    {
        base.Link();
        string Query = "INSERT INTO students (fnam, lnam, cod, idZone) VALUES ( '{0}', '{1}', '{2}', {3} )";
        Query = string.Format(Query, fnam, lnam, cod, idZone);
        base.commanddatatext(Query);
        base.UnLink();

我的代码:

    page_load:
    BL_students_new F = new BL_students_new();
    DropDownList1.Items.Clear();
    DropDownList1.DataSource = F.ddl();
    DropDownList1.DataTextField = "nam";
    DropDownList1.DataValueField = "idZone";
    DropDownList1.DataBind();

        btn_insert:
        BL_students_new F = new BL_students_new();
        F.fnam = TextBox1.Text.Trim();
        F.lnam = TextBox2.Text.Trim();
        F.cod = TextBox3.Text.Trim();
        F.idZone = Convert.ToInt32(DropDownList1.SelectedItem.Value);
        F.insert();

它可以保存所有东西,但是下拉列表的值不能被保存。请注意,我的下拉列表有文本和整数值,我需要这个值被保存。但是它失败了。(我的 DA 也没问题。)


“Fails” 失败在哪里?具体是什么情况?有错误吗?记录是否被插入但没有该值?在调试时,特别是该值丢失的具体位置在哪里? - David
@David,它保存了ddl的第一个索引。而不是我的选择。 - Reza Mezerji
根据发布的代码,您在绑定列表后立即保存记录。 因此,您永远没有机会做出选择或输入任何值。 - David
@David 我设置了 F.idZone,然后调用了 F.insert()。接下来我该怎么做? - Reza Mezerji
在实际与表单交互之后,您应该将表单值插入数据库。您上一个代码片段中的代码行大约需要执行一毫秒。在此期间,您还没有更改所选值。(由于这是ASP.NET,在此时您甚至还没有看到下拉列表。)因此,当您选择一个值时,数据库插入已经完成了。 - David
@David,非常抱歉。我已经纠正了我的代码。下拉列表的填充在页面加载时进行,插入操作在btn_insert中执行。 - Reza Mezerji
1个回答

1

根据您上面的评论:

填充 ddl 在 Page_Load 中,插入在 btn_insert 中

Page_Load 发生在 btn_Insert 之前。 这发生在每次请求页面时,无论是否是“post back”。(毕竟,在它了解 HTTP 请求的性质之前,页面必须加载到可用状态。)

所以正在发生以下情况:

  1. 绑定 DropDownList 选项
  2. 向用户显示页面
  3. 用户选择一个选项并提交
  4. 重新绑定 DropDownList 选项,丢失用户所选内容
  5. 插入到数据库

在 WebForms 中解决这个问题的简单方法是将您的 DropDownList 绑定逻辑包装在对 IsPostBack 的条件中。类似这样:

// in Page_Load:
if (!IsPostBack)
{
    BL_students_new F = new BL_students_new();
    DropDownList1.Items.Clear();
    DropDownList1.DataSource = F.ddl();
    DropDownList1.DataTextField = "nam";
    DropDownList1.DataValueField = "idZone";
    DropDownList1.DataBind();
}

那样的话,当用户提交表单时,你只需在页面最初请求时填充 DropDownList,而不是每次都填充。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接