Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1
ASP.NET MVC 5
Q : 如何將Controller程式碼,改用AsyncController來回傳DB資料,然後將資料顯示在View上?
A:
若目前有Controller如下,利用Entity Framework查詢DB資料出來:
public class OperaController : Controller {
private OperaContext context = new OperaContext( );
public ActionResult Index( ) {
return View( context.Operas.ToList( ) );
}
}
目前Index View如下
@model IEnumerable<Mod06_01.Models.Opera>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table border="1">
<tr>
<th>@Html.DisplayNameFor( m => m.Title )</th>
<th>@Html.DisplayNameFor( m => m.Year )</th>
<th>@Html.DisplayNameFor( m => m.Composer )</th>
</tr>
@foreach ( var item in Model ) {
<tr>
<td>@Html.DisplayFor( mi => item.Title )</td>
<td>@Html.DisplayFor( mi => item.Year )</td>
<td>@Html.DisplayFor( mi => item.Composer )</td>
</tr>
}
</table>
</div>
</body>
</html>
目前執行結果:
改用AsyncController,修改程式如下:
private OperaContext context = new OperaContext( );
public async Task<ActionResult> IndexAsync( ) {
var r = await context.Operas.ToListAsync( );
return View( r );
}
}
測試執行結果:
沒有留言:
張貼留言