Sunday, August 3, 2014

WebGrid Example using MVC

My objective is to add WebGrid pagination in MVC webapps.
Expected output:




















Step1: First add WebGrid plugin in your project. 

For adding go to tools >> Library Package Manager >> NutGut package for solution >> search by WebGrid and then install.

Step2: Open your views and add below code.

@model IEnumerable<ContosoUniversity.Models.Course>

@{
    ViewBag.Title = "Course";
}

<h2>Course</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<h2>
    Course Details
</h2>

@{
var grid = new WebGrid(source: Model, rowsPerPage: 5, canPage: true, canSort: true);
@grid.GetHtml(columns:grid.Columns(  
grid.Column(columnName:"Title", header:"Title"),
grid.Column(columnName: "Credits", header: "Credits"),
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.CourseID} )),
grid.Column(format: (item) => Html.ActionLink("Details", "Details", new { id = item.CourseID })),
grid.Column(format: (item) => Html.ActionLink("Delete", "Delete", new { id = item.CourseID }))
)
)
}

Step3: Open your controller and add below code.

private SchoolContext db = new SchoolContext();

        //
        // GET: /Course/

        public ActionResult Index(int? page)
        {
            return View(db.Courses.ToList());
        }

Step4: Now run your application and then you will get above output. 

Let me know if you have any issues.


No comments: