如何将数据保存到SQL Server表中?

时间:2019-05-05 00:42:45

标签: c# sql-server asp.net-mvc

我正在研究ASP.NET MVC应用程序。我需要从用户那里获取姓名和姓氏,然后将其保存到数据库中。

我编码了所有必要的部分。输入名称和姓氏时,程序将名称和姓氏正确保存到数据库中(我从SQL Server Management Studio中进行了检查),但是在屏幕上看不到它们。

这是我对应的索引视图。

@model System.Data.DataTable

@{
    Layout = null;
}

<table class="table table-bordered table-striped table">
    <tr>
        <th>Name</th>
        <th>Surname</th>
    </tr>
    @for (int i = 0; i < Model.Rows.Count; i++)
    {
        <tr>
            <td> @Model.Rows [i][1] </td>
            <td> @Model.Rows [i][2] </td>

        </tr>
    }
</table>
<hr>
<a href="@Url.Action("Create","Renter")">Add Person</a>

Index操作方法:

    public ActionResult Index()
    {
        DataTable peopletbl = new DataTable();

        using (SqlConnection sqlcon = new SqlConnection(connectionString)) {
            sqlcon.Open();
            SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Person", sqlcon);
            sqlDa.Fill(peopletbl);
        }

        return View(peopletbl);
    }

程序产生以下行:

wrong output

1 个答案:

答案 0 :(得分:0)

            //simulating data 
            DataTable peopletbl = new DataTable("Person");
            peopletbl.Columns.Add("Name", typeof(string));
            peopletbl.Columns.Add("SurName", typeof(string));

            DataRow row = peopletbl.NewRow();
            row["Name"] = "Alan";
            row["SurName"] = "Turing";

            peopletbl.Rows.Add(row);
            //until now, you already have the data    

            //at the view.....
            //just use index properly
            foreach (DataRow iRow in peopletbl.Rows)
            {
                var name = iRow["Name"];
                var surName = iRow["SurName"];
            }