SIGN UP MEMBER LOGIN:    
ARTICLE

WebGrid in ASP.Net MVC3 Razor with Entity Framework

Posted by Shirsendu Nandi Articles | ASP.NET MVC with C# May 30, 2011
In this article I will describe how to bind data from database in to MVC3 WebGrid using Entity Framework.
Reader Level:
Download Files:
 


Step 1:

Create a new ASP.Net MVC 3 application with an empty web application. While creating the project check the radio button "UnitTest".

Step 2:

Now under the "Model" folder create two classes.

  1. Blog
  2. Comments

    MVC3Razor1.gif

Step 3:

Now In the Blog Class Copy the following code:

public class Blog
    {
       
        [Key]      
        public int BlogId { get; set; }

        [Required(ErrorMessage = "BlogName is required")]
        public string BlogName { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(120, ErrorMessage = "Description Name Not exceed more than 120 words")]
        public string Description { get; set; }
        public string Body { get; set; }

        public virtual  List<Comments > Comments_List { get; set; }

    }

See here is the validation of each property. And also hold the list of comments. That means 1 blog contains many posts. So that is a one to many relationship.

The "Virtual" keywords means it will make the relationship.

Step 4:

Now in the Comments class write the following code:

public class Comments
    {
        [Key ]
        public int CommentId { get; set; }
          public string Comment { get; set; }
        //[ForeignKey]
          public int BlogId { get; set; }
          public virtual Blog Blog { get; set; }
 
    }

See here we also have the object reference of the "blog" class. Before that I have used the virtual key word.

Step 5:

Now it's time to make the entity class by which the database and the table will create.

Create a "DatabaseContext" folder under the project. After that create a class named "BlogDbContext.cs" under the folder. This class is an entity class.

Step 6:

Now make a reference for the Entity Framework by clicking "Add Reference" under the project.

MVC3Razor2.gif

In my project I had already provided the dll. Without this dll the table cannot be created in the database by object class mapping.

Now paste the following code into the "BlogDbContext" class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using blogmvc3.Models;

namespace blogmvc3.DatabaseContext
{
    public class BlogDbContext:DbContext
    {
        public DbSet<Blog> Blog { get; set; }
        public DbSet<Comments> Comments { get; set; }
    }
}

See here in the Dbset we are passing a blog class and a comments class. The Dbset will create a table automatically with a relation in the database.

The Namespace "System.Data.Entity" is very important for that.

Step 7:

Now we have to configure the "web.config" file for the connection string. The web.config file is under the Main Solution Project. Not the Project web.config file.

MVC3Razor3.gif

Now paste the following connection string into the web.config file.

<connectionStrings>

    <add name="BlogDBContext" connectionString="data source=.;Database=Blogdb;Trusted_Connection=true;" providerName="System.Data.SqlClient" />
  </connectionStrings>

MVC3Razor4.gif

Step 8:

Now create a Controller Class named "HomeController" under the "ControllerFolder. After that check the
"Add action for create.update,delete.." so it will automatically create the action mrthod in the Controller class.

MVC3Razor5.gif

MVC3Razor6.gif

Step 9:

Now in the "HomeController" Class first create an object of the "BlogDbContext" Class .

BlogDbContext _db = new BlogDbContext();

After that in the Index Method write the following code:

public ActionResult Index()
        {
            return View(_db.Comments .ToList ());
        }

Step 10:

Now create a master page in the Razor engine under the "shared" folder. Give it the name "_LayoutPage1.cshtml".

MVC3Razor7.gif

After that paste the following code there:

<!DOCTYPE html>

<html>
<
head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
   @*
<script src="../../Scripts/jquery-ui-1.8.11.custom.min.js" type="text/javascript"></script>
    <link href="../../Content/jquery-ui-1.8.11.custom.css" rel="stylesheet" type="text/css" />*@
</head>

<body>
    <div class="page">

        <div id="header">
            <div id="title">
                <h1>Blog Post</h1>
            </div
>

            <div id="logindisplay">
                @*@Html.Partial("_LogOnPartial")*@
            </div
>

            <div id="menucontainer">

                <ul id="menu">
                   @* <li>@html.actionlink("home", "index", "home")</li>*@
                    @*<li>@Html.ActionLink("About", "About", "Home")</li>*@
                   <li>@Html.ActionLink("home", "index", "home")</li>
                     <li>@Html.ActionLink("Article Post", "CreateLogin", "Article")</li>
                     @*<li>@Html.ActionLink("BookCab", "CreateLogin", "Cab")</li> *@
                </ul
>

            </div>
             <script type="text/javascript"><!--                 mce: 0--></script
>

        </div>

        <div id="main">
            @RenderBody()
            <div id="footer">
            </div>
        </div>
    </div
>
</body>
</
html>

Step 11:

Now go the "Home controller". Right-click the Index Method and add a view. It will look like:

MVC3Razor8.gif

Please check "Create Strongly-typed Views".

Choose Model Class "Comments" Under DropDown List.

Select "Scaffold Template" List. After that press the "Add" button. It will automatically create a view named "Index" under the "Home" folder.

Step 12:

See the Index View Engine will create code for the list view automatically.

Now delete all the code and replace it with the following code:

@model IEnumerable<blogmvc3.Models.Comments>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";

}
@{
    var grid = new WebGrid(source: Model, canPage: true, defaultSort: "BlogName", rowsPerPage: 3, canSort: true); 
   
}

<h2>Web grid</h2>
if (@Model != null ) 

 {    

  @grid.GetHtml(tableStyle:"grid",headerStyle: "head",  alternatingRowStyle: "alt",caption:"WebGrid"
           )
 
 }

<p>

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

Now see this code section what is written above.

MVC3Razor9.gif

See first we are creating the WebGrid and after that in the constructor parameter we are passing a different property argument such as paging property, sorting, and rows per page.

And in the second we are are calling the WebGrid by calling the "@Html.WebGrid" property. Here also we are passing a parameter for the WebGrid.

Now run the application; it will look like the following figure:

MVC3Razor10.gif

See here the BlogId and Comments are displaying in the WebGrid (marked with red). And the paging facility is also done (marked with black).

Conclusion: So in this article we have learned how to bind data into a WebGrid in to ASP.Net MVC3 Razor.
 

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor