MVC编辑视图上的重复条目

我有一个人物模型

[Table("Person")]
public class Person
{
    [Key]
    public int Id { get; set; }
    public int GenderId { get; set; }
}

还有性别模型

[Table("Gender")]
public class Gender
{
    public Gender()
    {
        People = new HashSet<Person>();
    }
    public virtual ICollection<Person> People { get; set; }

    [Key]
    public int Id { get; set; }
    public string Definition { get; set; } 
}

还有一个PersonViewModel

public class PersonViewModel
{
    [Key]
    public int? Id { get; set; }

    public IEnumerable<System.Web.Mvc.SelectListItem> Genders { get; set; }
    public string Gender { get; set; }  // For display purposes
    public int? GenderId { get; set; }
}

我有此方法从PersonId获取新的PersonViewModel(它将把Person的GenderId映射到PersonViewModel的GenderId),然后用对显示友好的Gender字符串和SelectListItem填充ViewModel

public personViewModel GetpersonViewModel(int personId)
{
    personViewModel personViewModel = (GetPersonViewModelFromId(personId));

    personViewModel.Genders = new GenderMethods().GetAsSelectListItem();
    personViewModel.Gender = personViewModel.Genders
        .Where(x => x.Value == personViewModel.GenderId
        .ToString())
        .FirstOrDefault().Text;

    return personViewModel;
}

最后,在“视图”中,我成功显示了下拉列表,并使用用户友好的“性别”字符串作为显示文本,以显示此人当前的性别。

@using (Html.BeginForm())
{
    @Html.DropDownListFor(model => model.GenderId, Model.Genders, Model.Gender)
    <input type="submit" value="Save" />
}

I suspect I shouldn't NEED a display-friendly string property on my ViewModel to be able to display the current Gender.Definition, and the big issue I've just discovered with this technique is that the text in the dropdownlist isn't actually tied to Gender.Id - it's just a string which could be anything. If the user doesn't CHANGE the dropdownlist entry to one of the actual gender options then the save/update function won't work.

How do I get to show the PersonViewModel's GenderId as a Gender.Definition in the SelectListItem?

评论