首先在VIEW前面宣告如下
@using mvc3.Models;
@{
ViewBag.Title = "index";
Model aa = new Model();
var grid = new WebGrid(aa.gridv(), canPage: true, rowsPerPage: 15,
selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
}
接著是在需要呈現的HTML如下
<div id="gridContent">
@grid.GetHtml(
columns: grid.Columns(
grid.Column("id", "id"),
grid.Column("item", "item"),
grid.Column("name", "改字", style: "description")
))
</div>
在MODEL的程式碼如下
public class data
{
public string id { get; set; }
public string item { get; set; }
public string name { get; set; }
}
public List<data> gridv()
{
string a = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(a);
conn.Open();
string sql = "select [id],[item],[cs] from item";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
List<data> oop = new List<data>();
while(dr.Read())
{
oop.Add(new data()
{
id = dr[0].ToString(),
item = dr[1].ToString(),
name = dr[2].ToString()
});
}
dr.Close();
dr.Dispose();
cmd.Dispose();
conn.Close();
conn.Dispose();
return oop;
}
不用WebGrid的方法如下
@foreach (var d in aa.gridv()){
<table>
<tr><td>@d.id</td><td>@d.item</td><td>@d.name</td></tr>
</table>
}
沒有留言:
張貼留言