MVC显示适当的值而不是Key

时间:2014-09-25 15:13:00

标签: asp.net-mvc

假设我们有一个表:

Person[ID,NAME,GENDER]
id = 1, name = Mozart, gender = 1
id = 2, name = Sissy, gender = 2
...

我有 KeyValuePair 集合

key = 1, value = MALE
key = 2, value = FEMALE
...

如何在MVC View上显示其值而不是性别?

like this:
---------
Persons
1 | Mozart | MALE
2 | Sissy | FEMALE
---------

Controller和View尽可能简单:

public class HomeController : Controller {
    public List<KeyValuePair<int, string>> genders = new List<KeyValuePair<int, string>>();
    public ActionResult Index() {
        genders.Add(1, "male");
        genders.Add(2, "female");

        return View( dbContext.Persons.ToList() );
    }
}

@model IEnumerable<Models.Person>
...
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.gender)
        </td>
        <td>
            @Html.ActionLink("Edit", "UserEdit", new { id = item.id }) |
            @Html.ActionLink("Delete", "UserDelete", new { id = item.id })
        </td>
    </tr>
}

谢谢

1 个答案:

答案 0 :(得分:2)

实现此目标的最简单方法是创建一个包含您所需属性的视图模型。

查看模型

public class PersonViewModel{
    public int Id {get;set;}

    public string Name {get;set;}

    public string Gender {get;set;}
}

现在,当您填充此视图模型时,您可以直接在代码中进行查找并传递相应的信息

var genderDictionary = new Dictionary<int, string>();
genderDictionary.Add(1, "Male");
genderDictionary.Add(2, "Female");
var people = db.Persons.ToList().Select(x=>new PersonViewModel{
     Id = x.Id, 
     Name = x.Name,
     Gender = genderDictionary[x.Gender]
});
return people;

最后,您的视图模型应更新为以下

@Model IEnumerable<Namespace.PersonViewModel>

或者,您可以将字典传递给viewdata对象中的视图。然后,在进行循环并在那里执行查找时使用它。但是,使用强类型视图(如上所述)是进行.NET MVC开发时更好的做法。这里更多的是信息而不是&#34;你应该怎么做&#34;。

<强>控制器

public ActionResult People(){

   var model = db.Persons.ToList();
   ViewData["genderDictionary"] = yourKeyValuePair;
   return View(model);
}

查看

@{
  var genderDictionary = (Dictionary<int, string>)ViewData["genderDictionary"];
  foreach(var person in Model){
     <tr>
        <td>@person.Name</td>
        <td>@genderDictionary[person.Gender]</td>
     </tr>
  }
}