Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DisplayFor() to show what was selected from a drop down list

Tags:

c#

asp.net-mvc

So drop down lists have value/text. The value is what I store in my database (as it's the primary key to a table that lists value/text to show in the drop down list). When I populate my drop down I use the value/text. When a user selects it stores the value (numeric) to the transaction table. This means when I read it back into my model I have the number value and not the text. However, after 24 hours of the selection I need to only display the text as they can't make changes. The issue is it's display the value (1, 2, 3, 4) instead of the actual text which would make more sense to humans.

Is there a way to convert this at the view level? The reason I ask is because my template branches off and acts as a display template and editor template because that's the functionality required on the page. So I easily show the selected value in the editor template sections via:

@Html.DropDownListFor(modelItem => item.RecordType, new SelectList(Model.RecordTypes, "RECORD_TYPE_ID", "RECORD_TYPE", item.RecordType)

but the display section has:

@Html.DisplayFor(modelItem => item.RecordType)

Which gives me the value number and not the text. Do I really have to make another field in my view model and populate per record the text as well as the value? As you can see from the DropDownListFor() I have the RecordTypes list that stores the value/text so can I use the value to find the text and display that from the template view via DisplayFor() or something other function?

like image 673
user441521 Avatar asked Sep 30 '22 19:09

user441521


1 Answers

One alternative might be:

@Html.DisplayFor(modelItem =>
    Model.RecordTypes.FirstOrDefault(rt => rt.RECORD_TYPE_ID == item.RecordType))

UPDATE: as stated in the comment, the right approach ended up being:

@Model.RecordTypes.FirstOrDefault(rt => rt.RECORD_TYPE_ID == item.RecordType).RECORD_TYPE.ToString()

which simply displays the string value.

like image 162
Mike Perrenoud Avatar answered Oct 03 '22 09:10

Mike Perrenoud