user1477388
user1477388

Reputation: 21440

ASP MVC SelectList() Name Concatenation

I have the following code which works:

ViewBag.Resources = New SelectList(db1.Tbl_Resources, "Resource_ID", "Resource_FirstName")

I want to not only show the first name, but also the last name so I tried this:

ViewBag.Resources = New SelectList(db1.Tbl_Resources, "Resource_ID", "Resource_FirstName" + " " + "Resource_LastName")

However, it didn't work because it seems to look for a model property called "Resource_FirstNameResource_LastName." How can I concatenate these for use in the SelectList() method?

Upvotes: 1

Views: 2748

Answers (1)

Pepto
Pepto

Reputation: 1444

Because the SelectList constructor in Mvc uses the dataTextField argument and reflection to "pull" the property value at runtime, there's no way to accomplish what you are doing there HOWEVER, a simple workaround

Create a new readonly properly on your table class (use partial class if using EF) called "Caption" for example. Then in the getter return Resource_FirstName" + " " + Resource_LastName

class db1.Tbl_Resources
{
    public string Caption { get {return Resource_FirstName + " " + Resource_LastName;}}
}

Then in your View or Helper

New SelectList(db1.Tbl_Resources, "Resource_ID", "Caption");

At least that's how I handle that scenario, which is fairly common.

Upvotes: 7

Related Questions