2012-06-14 21 views
8

soy capaz de utilizar WebGrid en cualquier controlador como:¿Cómo usar WebGrid en una vista cshtml?

var grid = new WebGrid(emailsFetched, columnNames);

he tenido que añadir una referencia en mi proyecto de ASP.NET MVC para System.Web.Helpers para esto.

Pero cuando trato de utilizar esta rejilla web en vista directamente (para evitar la creación de instancias y otros ajustes en el controlador) que dice: The type or namespace 'WebGrid' cannot be found. Ok, he intentado añadir una referencia aquí también:

@using System.Web.Helpers pero esto plantea otro problema:

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'.

Esto es bastante extraño ... He visto suficiente ejemplo de red que están utilizando WebGrid y no tiene que declarar nada en la vista cshtml ...

¿Puede decirme cómo solucionar esto? ¿O por qué me encuentro con este tema tan feo?

Respuesta

22

Finalmente he podido notar que esto:

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

tiene que ser añadido en web.config, bajo system.web sección, withing compilation etiquetas por lo que se verá así:

<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> 
6

Trate de seguir los pasos a continuación que se habían probado antes en un proyecto ASP.NET MVC4 sin ningún problema.

1) abierto NuGet Package Manager en Visual Studio y la búsqueda “Microsoft-web-ayudante” e instalar.

2) Después de instalarlo abrir web.config en su solución y cambie connectionStringName parámetro para DefaultMembershipProvider, DefaultRoleProvider cinco DefaultSessionProvider (si no lo hace, puede encontrarse con 'DefaultConnection' no se encontró en la configuración de aplicaciones o la cadena de conexión es vacío. "error.

3) Reconstruya su proyecto y luego use una definición similar a la siguiente en la vista de la máquina de afeitar.

Nota: Cambio "Título","Controller" y "acción" nombres en Html.ActionLinks acuerdo a su proyecto.

Vista:

@{ 
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 
) 


Aquí están las clases de abajo css utilizado en Razor.Si desea utilizar sus definiciones css, simplemente cambie las propiedades de estilo a las suyas (algunas propiedades son opcionales como las del 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> 
} 


Espero que esto ayude ...

0

encontré con este problema. Realmente no puedo tomar el crédito, pero desinstalé la versión anterior y volví a instalar la última versión de Microsoft ASP.NET MVC4 de Nuget y todo me funciona. Espero que esto ayude a alguien más. Intenté todas las soluciones, pero esto fue lo único que funcionó. http://forums.asp.net/t/1823940.aspx?MVC4+WebGrid+problem+in+View+Razor+

Cuestiones relacionadas