asp.net mvc and linq to entities: how to include text value from IEnumerable<SelectListItem>

牧云@^-^@ 提交于 2020-01-01 18:14:40

问题


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 all 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" }
    };
  }

}

回答1:


Enum.GetName(typeof(MessageTypes), item.Message_Type)




回答2:


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>


来源:https://stackoverflow.com/questions/1785410/asp-net-mvc-and-linq-to-entities-how-to-include-text-value-from-ienumerablesel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!