2

I am trying to format a WebGrid column so I can concatenate two pieces of data together (first and last name). Here is what I'm trying, but I will admit I don't think I fully understand how to use the data (besides the basic scenarios) in WebGrid. (To the column name, the Teacher object is being passed to my view, but to actually get the teacher's name, I have to get that information from the linked user object since users can play multiple roles.)

grid.Column(
    columnName: "Teacher.User",
    header: "Teacher",
    style: "",
    canSort: true,
    format: (item) =>
        {
            var text = Html.DisplayTextFor(item => item.LastName) + ", " + Html.DisplayTextFor(item => item.FirstName);
            return Html.Raw(text);
        }
)
JasCav
  • 34,458
  • 20
  • 113
  • 170

2 Answers2

12

Simplest way to concatenate two pieces of data together, follow this

grid.Column("FullName", format: (item) => item.LastName+ ' ' + item.FirstName)
antyrat
  • 27,479
  • 9
  • 75
  • 76
Thilanka
  • 121
  • 1
  • 3
2

Strongly typed helpers that take lambda expressions don't work with dynamic expressions which is what the WebGrid helper is drowned with. The item argument that is passed to the format function is of type dynamic so you cannot use it with lambda expressions.

I am trying to format a WebGrid column so I can concatenate two pieces of data together (first and last name

What an excellent candidate for a view model. Just add another property in your User view model:

public string FullName 
{ 
    get 
    {
        return string.Format("{0}, {1}", this.LastName, this.FirstName);
    }
}

that you will use in the view:

grid.Column(
    columnName: "Teacher.User.FullName",
    header: "Teacher",
    style: "",
    canSort: true
)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Well...um...sure...if you want to make it EASY. (Wow...I most definitely was trying to use a screwdriver to pound in a nail and didn't even think to try to pick up the hammer.) – JasCav Dec 29 '11 at 15:54
  • In regard to your update ("strongly typed helpers..."), why did this work so well? http://stackoverflow.com/questions/6894313/mvc3-webgrid-custom-text-in-column – JasCav Dec 29 '11 at 16:05
  • 2
    @JasCav, by strongly typed help I mean one that takes a lambda expression such as EditorFor, DisplayFor, TextBoxFor, ... In the example you have shown none of those helpers is used. `Html.ActionLink` is not a strongly typed helper. In this helper the arguments are simple types, not lambda expressions. – Darin Dimitrov Dec 29 '11 at 16:09