JasCav
JasCav

Reputation: 34632

Formatting WebGrid Column to Contain Two Pieces of Data

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);
        }
)

Upvotes: 2

Views: 10070

Answers (2)

Thilanka
Thilanka

Reputation: 121

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

grid.Column("FullName", format: (item) => item.LastName+ ' ' + item.FirstName)

Upvotes: 12

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

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
)

Upvotes: 2

Related Questions