jueves, enero 12, 2012

Ejemplo de uso de WebGrid en Razor

Untitled Page

Definición del HTML que contiene un grid, utilizando sintaxis Razor

@model IEnumerable<Dream.Models.Articulo>
 
@{
    if (Model != null)
    {
        var grid = new WebGrid(
            source: Model,
            canPage: false,
            canSort: false
            );
 
            @grid.GetHtml(
                //rowStyle: @MyHelpers.Utils.GetArticleLineStyleClass(p => p.codProdAE, 5),
                //"font-size:1.3em",
                columns: new[] {
                    grid.Column("marca""Fabricante",
                    format: p => @MyHelpers.HtmlHelpers.GetArticleLineStyleClass(p.codProdAE, p.stock, p.marca),
                    style: "leftAlign"
                    ),
                    grid.Column("articulo""Ref. Fabricante",
                    format: p => @MyHelpers.HtmlHelpers.GetArticleLineStyleClass(p.codProdAE, p.stock, p.articulo),
                    style: "leftAlign"
                    ),
                    grid.Column("codProdAE""Ref. Autoequip",
                    format: p => @MyHelpers.HtmlHelpers.GetArticleLineStyleClass(p.codProdAE, p.stock, p.codProdAE, false),
                    style: "centerAlign200"
                    ),
                    grid.Column("stock""Stock", 
                    format: p => @MyHelpers.HtmlHelpers.GetArticleLineStyleClass(p.codProdAE, p.stock, p.stock.ToString(), false),
                    //format: p => (p.codProdAE == "") ? "" : p.stock.ToString() + "  ",
                    style: "centerAlign50"
                    ) /*,
                    grid.Column("precioConIVA", "P.V.P.",
                    format: p => @MyHelpers.Utils.GetArticleLineStyleClass(p.codProdAE, p.stock, p.precioConIVA.ToString() + " €", false),
                    style: "rightAlign"
                    )*/
            }
        )
    }
}

Helper que retorna un <p> con diferentes class en función de los parámetros que se le pasen:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace MyHelpers
{
 public static class HtmlHelpers
 {
  public static MvcHtmlString GetArticleLineStyleClass(string codProdAE, decimal stock, string text, bool showIfThereIsNoCodProd = true)
  {
   var builder_p = new TagBuilder("p") { InnerHtml = text };
 
   if (codProdAE == null)
    if (!showIfThereIsNoCodProd)
     builder_p.InnerHtml = "";
    else
     builder_p.Attributes.Add("class""gridRowWithoutCodProdAutoequip");
   else if (stock == 0)
    builder_p.Attributes.Add("class""gridRowWithoutStock");
   else
    builder_p.Attributes.Add("class""gridRowWithStock");
 
   return MvcHtmlString.Create(builder_p.ToString(TagRenderMode.Normal));
  }
        }
}