Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WebGrid in a cshtml view?

I am able to use WebGrid in any controller like:

var grid = new WebGrid(emailsFetched, columnNames);

I had to add a reference in my ASP.NET MVC project to System.Web.Helpers for this.

But when I try to use this web grid in view directly (to avoid instantiation and other settings in controller) it says: The type or namespace 'WebGrid' cannot be found. Ok, I tried to add a reference here too:

@using System.Web.Helpers but this throws another issue:

There is no build provider registered for the extension '.cshtml'. You can register one in the <compilation><buildProviders> section in the machine.config or web.config. Make sure is has a BuildProviderAppliesToAttribute attribute which includes the value 'Web' or 'All'.

This is pretty strange... I've seen enough example on net which are using WebGrid and don't have to declare anything in the cshtml view...

Can you please tell me how to solve this? Or why I encounter this very ugly issue?

like image 518
Cristian Boariu Avatar asked Jun 14 '12 23:06

Cristian Boariu


People also ask

What is WebGrid in ASP NET MVC?

In ASP.NET MVC, the new concept begins WebGrid. WebGrid is lightweight for showing data in report format. As you know, MVC is all about Model View Controller, in this article we will learn how to create a WebGrid and search data and show it in a WebGrid with Entity Framework.

How do you use a model in razor view?

Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.

What is @model in Cshtml?

The @model directive allows access to the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object: CSHTML Copy.

How do I view Cshtml?

Right click the Index. cshtml file and select View in Browser. You can also right click the Index. cshtml file and select View in Page Inspector.


2 Answers

Finally I've been able to notice that this:

<assemblies> <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies>

has to be added in web config, under system.web section, withing compilation tags so it will look like:

<system.web>
    <compilation debug="true" targetFramework="4.0">
        <assemblies>
            <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </assemblies>
    </compilation>
</system.web>
like image 191
Cristian Boariu Avatar answered Oct 19 '22 15:10

Cristian Boariu


Try to follow the steps below that had been tested before in an ASP.NET MVC4 project without any problem.

1) Open NuGet Package Manager in Visual Studio and search “microsoft-web-helper” and install.

2) After installing it open web.config in your solution and change connectionStringName parameter for DefaultMembershipProvider, DefaultRoleProvider ve DefaultSessionProvider (if you do not, you might encounter 'DefaultConnection' was not found in the applications configuration or the connection string is empty.” error.

3) Rebuild your project and then use a smilar definition like below in your razor view.

Note: Change "Title", "Controller" and "Action" names in Html.ActionLinks according to your project.

View:

@{
var grid = new System.Web.Helpers.WebGrid(
    source: Model,
    columnNames: new List<string>() { "Title" },
    ajaxUpdateContainerId: "myGrid",
    defaultSort: "Name",
    canPage: true,
    canSort: true,
    rowsPerPage: 5
    );
grid.SortDirection = SortDirection.Ascending;
}


@grid.GetHtml(
      tableStyle: "table", /*your class name for this property*/
      headerStyle: "webgrid-header",/*your class name for this property*/
      footerStyle: "webgrid-footer", /*your class name for this property*/
      rowStyle: "webgrid-row-style", /*your class name for this property*/
      alternatingRowStyle: "webgrid-alternating-row",/*your class name...*/                                         selectedRowStyle: "webgrid-selected-row",/*your class name for this property*/

      firstText: "<<",
      lastText: ">>",
      mode: WebGridPagerModes.All,
      fillEmptyRows: true,

      columns: grid.Columns(
       grid.Column("ApplicantID", "No", style: "span1", canSort: true),
       grid.Column("Name", "Name", style: "span2", canSort: true),
       grid.Column("Surname", "Surname", style: "span2", canSort: true),
       grid.Column("Organization", "Org.", style: "span2", canSort: true),
       grid.Column("MeetingId", "Meeting", style: "span1", canSort: true),
        //some format usage samples:
        //grid.Column("Email", "e-mail", style: "span1", canSort: true, format: @<a href="mailto:@item.Email">@item.Email</a>),  
        //grid.Column("BirthDate", format: p=>p.BirthDate.ToShortDateString()),

//for using multiple Html.ActionLink in a column using Webgrid
grid.Column("Operations", format: (item) =>
 new HtmlString(
       Html.ActionLink("Show Details", "Edit", "Admin", new
       {
           applicantId = item.ApplicantID,               
           title = "Detail",
           @class = "icon-link",
           style = "background-image: url('../../Content/icons/detail.png')"
       }, null).ToString() +
       Html.ActionLink("Edit Record", "Edit", "Admin", new
       {
           applicantId = item.ApplicantID, 
           title = "Edit",
           @class = "icon-link",
           style = "background-image: url('../../Content/icons/edit.png')"
       }, null).ToString() +
       Html.ActionLink("Delete Record", "Edit", "Admin", new
       {
           applicantId = item.ApplicantID,
           title = "Delete",
           @class = "icon-link",
           style = "background-image: url('../../Content/icons/delete.png')"
       }, null).ToString()
 )
)
),
numericLinksCount: 5
)


Here are the css classes below used in Razor. If you would like to use your css definitions simply change style properties to that of yours (Some properties are optional as the ones in the Razor View).

<style type="text/css">    
    .webgrid-operations { /*for limiting the width of Operations 
                          menu used in the WebGrid*/
    width: 65px;
}

.webgrid-header td {
    text-align: left;
}

.webgrid-header th {
    background-color: #EFEFEF;
    margin-bottom: 2px;
}

.webgrid td {
    padding-right: 15px;
}

.webgrid-footer td {
    font-family: 'open_sanssemibold', sans-serif;
    font-size: 1em;
    text-align: right !important;
    padding-right: 21px !important;
    color: #000;
    background-color: #EFEFEF;
}

    .webgrid-footer td a {
        text-align: right !important;
        padding: 0 .4em 0 .4em;
        font-size: .83em;
        text-decoration: none;
        color: #FFFFFF;
        border: 1px solid #C0C0C0;
        background-color: #808080;
    }

        .webgrid-footer td a:hover {
            background-color: #6BBEC7;
        }

        .webgrid-footer td a.selected {
            background-color: #f00;
            color: #f00;
        }

.webgrid a {
    color: #fff;
}

.colRowButton {
    width: 70px;
    text-align: left;
}

.webgrid-row-style {
    /*border-bottom: 1px solid #E8EEF4;*/
}

.webgrid-alternating-row td {
    /*background-color: #f9f9f9;*/
}

.webgrid-selected-row {
    /*font-weight: bold;*/
}    

<style type="text/css">
    a.icon-link {
        background-color: transparent; 
        background-repeat: no-repeat; 
        background-position: 0px 0px;
        border: none;
        cursor: pointer; 
        width: 16px;
        height: 16px;
        margin-right: 8px; 
        vertical-align: middle;
    }

    .span5 {
    width:380px
    }
    .span4 {
    width:300px
    }
    .span3 {
    width:220px
    }
    .span2 {
    width:140px
    }
    .span1 {
    width:60px
    }
    </style>
}


Hope this helps...

like image 21
Murat Yıldız Avatar answered Oct 19 '22 15:10

Murat Yıldız