Vince Ashby-Smith
Vince Ashby-Smith

Reputation: 1192

How to get name from id

Hi all i'm struggling with this a bit and wonder if someone could lend a hand. I have the following view:

@model IEnumerable<TelephoneNumber.Models.Number>

<table>
    <tr>
        <th>
            Number
        </th>
        <th>
            Status
        </th>
    </tr>

    @foreach (var item in Model) {
    <tr>
        <td>
            @item.Number1   
        </td>
        <td>
            @item.StatusID  
        </td>
    </tr>
}
</table>

This is all fine and good, however returning the StatusID to the user isn't very friendly. We store the Status name in the Status object. However how can i get the name for the StatusID associated to each telephone number record?

Upvotes: 0

Views: 532

Answers (4)

Henry
Henry

Reputation: 1008

How about @item.Status.StatusName; assuming you have parent to child relationship between Telephone StatusId and Status StatusId.

Upvotes: 1

musefan
musefan

Reputation: 48415

Your Models.Number class needs to hold this information. So add one of the following properties to this class...

string StatusName;
//or
Status Status;

Then in your logic processing you need to set this value. You can use the StatusID value you already have to retrieve the Status model and use its values to assign to the Number class.

Then in you view you just call the property you want..

@item.StatusName
//or
@item.Status.Name

Upvotes: 0

Adam Tuliper
Adam Tuliper

Reputation: 30152

You should have a Status table relationship I'm assuming tied to this in which case you will need to make your query

.Include("Statuses") 

the Status table unless this is an enum , in which case read about the enum support in EF 4.1

http://blog.bennymichielsen.be/2011/05/21/entity-framework-4-1-supporting-enums/

If you have a Status table but don't have a relationship defined, now would be the time to do that : )

Upvotes: 0

Blindy
Blindy

Reputation: 67380

Personally I think you shouldn't expose ID's like that, you should convert them to meaningful expressions before creating your model (ie, join the tables and write the status name instead of the status id to your model).

That said, your choices are:

  • add another field to the model that represents the status name
  • throw the status table to the view bag and let the view figure it out (@ViewBag.Statuses.Single(w=>w.Id==Model.StatusID).Name)
  • stop using ID's :)

Upvotes: 0

Related Questions