asp.net mvc and linq to entities: how to include text value from IEnumerable<SelectListItem>
I have a table with a constraint on one field - it can be 1, 2 or 3. (The correct solution to this is probably to create a lookup table for this, but for now I'm wondering if it's possible to do this without the lookup table.)
I've created a class that returns an IEnumerable for the values. I'm using LINQ to Entities, and would like to be able to display the text value in a col. when listing a开发者_如何学Pythonll the entities.
The code for create/edit looks like:
Controller.cs:
ViewData["Message_Types"] = MessageTypes.MessageTypeList;
edit.aspx:
<%= Html.DropDownList("Message_Type",(IEnumerable<SelectListItem>)ViewData["Message_Types"]) %>
and the default model binding works just fine using TryModelUpdate:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection form)
{
...
TryUpdateModel(editItem, new string[] { "Message_Type" });
...
}
How However, I'd like to display the text value instead of the numeric value:
index.aspx:
<td>
<%= Html.Encode(item.Message_Type) %>
</td>
How can I get the text value of the element that corresponds to the item.Message_type?
Update:
The message types look like:
public static IEnumerable<SelectListItem> MessageTypeList
{
get
{
return new[] {
new SelectListItem{ Text = "Text Value 1", Value="1" },
new SelectListItem{ Text = "Text Value 2", Value="2" },
new SelectListItem{ Text = "Text Value 3", Value="3" }
};
}
}
Enum.GetName(typeof(MessageTypes), item.Message_Type)
This seems to work - not sure if it's the best solution or not though.
Instead of:
<td>
<%= Html.Encode(item.Message_Type) %>
</td>
I get the text value from:
<td>
<%= Html.Encode(MessageTypes.MessageTypeList.Single(foo => foo.Value == item.Message_Type.ToString()).Text)%>
</td>
精彩评论