我想显示由数据库使用 ADO.NET / ASP.NET MVC 生成的文本框中填充的标识列

I want to display identity column populated in textbox that is generated by database using ADO.NET / ASP.NET MVC

提问人:Divya 提问时间:9/25/2023 最后编辑:marc_sDivya 更新时间:9/25/2023 访问量:62

问:

模型类:Department

[Table("Department")]
public class Department
{
    [Display(Name ="Sno")]
    public int id { get; set; }
    [Display(Name = "Department_Id")]
    public String Dno { get; set; }
    [Required]
    [Display(Name ="Department_Name")]
    public String Dname { get; set; }
}

Repository 类

public List<Department> GetDepartmentList()
{
        connection();
        List<Department> list = new List<Department>();
        SqlCommand cmd = new SqlCommand("SpDepartmentList", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        con.Open();
        da.Fill(dt);
        con.Close();

        foreach (DataRow dr in dt.Rows)
        {
            list.Add(
                new Department
                {
                    id = Convert.ToInt32(dr["id"]),
                    Dno = Convert.ToString(dr["Dno"]),
                    Dname = Convert.ToString(dr["Dname"]),
                    //DnoList = Convert.To(dr["DnoList"])
                });
        }

        return list;
}

在类中使用 ADO.NET 提交数据:Repository

public bool AddDepartment(Department obj)
{
        connection();

        SqlCommand cmd = new SqlCommand("spAddDepartments", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Dname", obj.Dname);

        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (i >= 1)
        {
            return true;
        }
        else
        {
            return false;
        }
}

控制器

[HttpGet]
public ActionResult AddDepartment()
{
    // Here I want get Dno id displayed that is generated by 
    // database with that id I have to submit data to data table
    return View();
}

[HttpPost]
public ActionResult AddDepartment(Department Dep)
{
        try
        {
            if (ModelState.IsValid)
            {
                DepartmentRep Repo = new DepartmentRep();

                if (Repo.AddDepartment(Dep))
                {
                    ModelState.Clear();
                    ViewBag.Message = "Details added successfully";
                }
            }

            return View();
        }
        catch
        {
            return View();
        }
}

表定义:

CREATE TABLE [dbo].[Department] 
(
    [id] INT IDENTITY (1, 1) NOT NULL,
    [Dno] AS (CONCAT('Dno_', [id])),
    [Dname] VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Dno] ASC)
);

我已经填充了数据库自动生成的身份。有了这个 id,我必须使用 ADO.NET 将数据提交到表中的数据库。Dno

请谁能帮我?

我是这个网站的新手,如果我犯了任何错误,请原谅我。

C# asp.net sql-server asp.net-mvc ado.net

评论

0赞 Mohammad Aghazadeh 9/25/2023
欢迎来到stackoverflow,你想在哪里显示列?您尝试了什么,发生了什么错误?如果您不向我们提供此信息,我们不知道如何帮助您,请在发布新问题之前阅读此内容Dno
0赞 Divya 9/25/2023
感谢您的回复。我想使用“Dno”将数据提交到数据表。Dno是由数据库生成的。Dno 显示在浏览器上,不可编辑。Dno 和输入 Dname 的用户提交到 Department Table 。
0赞 Gert Arnold 9/25/2023
的代码是什么?spAddDepartments
0赞 Divya 9/26/2023
“CREATE 过程 spAddDepartments @Dname nvarchar(50)=null 开始插入 Department(Dname) 值 (@Dname) 结束”
0赞 Divya 9/26/2023
只是我想在不可编辑的文本框中显示“Dno”

答:

-1赞 Hezy Ziv 9/25/2023 #1

要显示数据库在添加新数据库时生成的(标识列),可以按照以下步骤操作:DnoDepartment

  1. 修改操作方法,以便在使用 ADO.NET 将数据插入数据库后获取生成的数据。AddDepartmentDno

  2. 将生成的数据传递到视图,以便将其显示给用户。Dno

以下是修改代码的方法:

控制器(将子句添加到 SQL 查询):OUTPUT

[HttpPost]
public ActionResult AddDepartment(Department Dep)
{
    try
    {
        if (ModelState.IsValid)
        {
            DepartmentRep Repo = new DepartmentRep();

            int generatedDno = Repo.AddDepartment(Dep); // Get the generated Dno

            if (generatedDno > 0)
            {
                ModelState.Clear();
                ViewBag.Message = "Details added successfully";
                ViewBag.GeneratedDno = generatedDno; // Pass the generated Dno to the view
            }
        }

        return View();
    }
    catch
    {
        return View();
    }
}

存储库(返回生成的 Dno):

public int AddDepartment(Department obj)
{
    connection();

    SqlCommand cmd = new SqlCommand("spAddDepartments", con);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("@Dname", obj.Dname);

    SqlParameter outputParam = new SqlParameter("@GeneratedDno", SqlDbType.Int)
    {
        Direction = ParameterDirection.Output // Define an OUTPUT parameter to get the generated Dno
    };
    cmd.Parameters.Add(outputParam);

    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();

    if (outputParam.Value != DBNull.Value)
    {
        return Convert.ToInt32(outputParam.Value); // Return the generated Dno
    }
    else
    {
        return 0;
    }
}

视图(显示生成的 Dno):

@{
    ViewBag.Title = "AddDepartment";
}

<h2>Add Department</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Department</h4>
        <hr />

        <div class="form-group">
            @Html.LabelFor(model => model.Dname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Dname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Dname, "", new { @class = "text-danger" })
            </div>
        </div>

        @if (ViewBag.GeneratedDno > 0)
        {
            <div class="form-group">
                <label class="control-label col-md-2">Generated Dno:</label>
                <div class="col-md-10">
                    @ViewBag.GeneratedDno
                </div>
            </div>
        }

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

在此修改后的代码中:

  • 存储库中的方法现在以 .它还在 SQL 命令中定义了一个参数,用于检索生成的 .AddDepartmentDnointOUTPUTDno

  • 控制器的操作方法现在从存储库中获取生成的数据,并使用 将其传递给视图。AddDepartmentDnoViewBag

  • 该视图检查是否大于 0(表示有效生成的 ),并在可用时将其显示给用户。ViewBag.GeneratedDnoDno