Cab*_*ath 4 c# database asp.net-mvc view
我一直在尝试在ASP.NET MVC项目中使用预先存在的数据库.我创建了一个"数据连接"到我的(Microsoft SQL)数据库(".\ SQLEXPRESS.Databases"),其中包含表"Test".该表有两列,"ID(int)"和"name(nvarchar(MAX))".
在"Models"文件夹中,我放了这个新类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcMovie.Models
{
public class Test
{
public int ID { get; set; }
public string name { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
然后(在"控制器"中)我有一个新的Controller,"HelloWorldController".在这我有这个功能:
public ActionResult Index()
{
DataSet data;
DataTable table;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT * FROM Test", connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = select;
data = new DataSet();
adapter.Fill(data, "Test");
table = data.Tables[0]; //is the [0] really correct?
}
return View(/* HOW DO I GET THE TABLE TO THE VIEW? */);
}
Run Code Online (Sandbox Code Playgroud)
现在我想在我的"Index.cshtml"文件中显示表格的行(在"视图"中).如何从Controller获取表到视图?我发现的是"@model"和"IEnumerable",但这不起作用,因为我无法转换我的表.
@model IEnumerable<MyProject.Models.Test>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var item in Model) {
<p>blaaaah</p>
}
Run Code Online (Sandbox Code Playgroud)
现在有三个问题:
1.我做错了什么吗?(DB-Access的方法,......)
2.有更简单的方法吗?(没有所有适配器,..东西)
3.如果!1 &&!2,我如何让它工作?(获取视图文件以"知道"我的表)
感谢您的帮助,
问候,
Caba
Dar*_*rov 12
我建议你使用视图模型并摆脱DataSet和Tables.让我们忘掉那些数据类型.他们是遗产.
例如,您可以使用一个方法(最终将其外部化为repositorhy以避免使用数据库访问来污染控制器代码):
public IEnumerable<Test> GetTests()
{
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT ID, name FROM Test";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Test
{
ID = reader.GetInt32(reader.GetOrdinal("ID")),
name = reader.GetString(reader.GetOrdinal("name")),
}
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的控制器动作:
public ActionResult Index()
{
IList<Test> tests = GetTests().ToList();
return View(tests);
}
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.最后相应的强类型视图显示结果:
@model IList<Test>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].ID)</td>
<td>@Html.DisplayFor(x => x[i].name)</td>
</tr>
}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
或者WebGrid如果您愿意,可以使用帮助:
@model IList<Test>
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17642 次 |
| 最近记录: |