Skip to content

Instantly share code, notes, and snippets.

@odrix
Created February 15, 2013 14:26

Revisions

  1. Adrien Bey created this gist Feb 15, 2013.
    10 changes: 10 additions & 0 deletions Employe.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    public class Employe
    {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }


    [Display(Name="Years of Experience", ShortName="Nb Exp")]
    public int ExpYear { get; set; }
    }
    27 changes: 27 additions & 0 deletions HtmlHelpers.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Linq.Expressions.Internal;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;

    public static class HtmlHelpers
    {
    public static string DisplayShortNameFor<TModel, TValue>(this global::System.Web.Mvc.HtmlHelper<global::System.Collections.Generic.IEnumerable<TModel>> t, global::System.Linq.Expressions.Expression<global::System.Func<TModel,TValue>> exp)
    {
    CustomAttributeNamedArgument? DisplayName = null;
    var prop = exp.Body as MemberExpression;
    if (prop != null)
    {
    var DisplayAttrib = (from c in prop.Member.GetCustomAttributesData()
    where c.AttributeType == typeof(DisplayAttribute)
    select c).FirstOrDefault();
    if(DisplayAttrib != null)
    DisplayName = DisplayAttrib.NamedArguments.Where(d => d.MemberName == "ShortName").FirstOrDefault();
    }
    return DisplayName.HasValue ? DisplayName.Value.TypedValue.Value.ToString() : "";
    }
    }
    27 changes: 27 additions & 0 deletions index.cshtml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    @model IEnumerable<testMVC4.Models.Collaborateur>
    @{ViewBag.Title = "Index";}
    <h2>Index</h2>
    <p>
    @Html.ActionLink("Create New", "Create")
    </p>
    <table>
    <tr>
    <th>@Html.DisplayNameFor(model => model.FirstName)</th>
    <th>@Html.DisplayNameFor(model => model.LastName)</th>
    <th>@Html.DisplayShortNameFor(model => model.ExpYear)</th>
    <th></th>
    </tr>

    @foreach (var item in Model) {
    <tr>
    <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
    <td>@Html.DisplayFor(modelItem => item.LastName)</td>
    <td>@Html.DisplayFor(modelItem => item.ExpYear)</td>
    <td>
    @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
    @Html.ActionLink("Details", "Details", new { id=item.Id }) |
    @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    </td>
    </tr>
    }
    </table>