2009-11-05 41 views
1

的基本想法是,你有一些类具有引用类型属性,像这样创建在asp.net mvc的一个创建/编辑视图/带的SelectList行动

public class Person 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public Country HomeCountry { get; set; } 
} 

public class Country 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

现在,如果你需要创建一个视图来编辑个人数据你没有任何名称或编号的问题,但你有国家;

目前我有两个基本的解决方案

NR1:的操作方法,我把 ViewData["Countries"] = countryService.GetAll(); 并在视图像这样的东西 SelectList(ViewData["Countries"], Country.Id

使用它,我要去有[后操作]创建(国家/地区)

nr2:创建PersonDto或PersonViewModel(同一件事我猜)

这里我就不得不创建(CountryVieModel countryViewModel),没有的ViewData

public class PersonViewModel 
    { 
    Person Person { get; set; } 
    public SelectList Countries { get; private set; } 


    public PersonViewModel(Person person) 
    { 
    Person = person; 
    var countryService = container.Resolve<CountryService>(); 
    Countries = new SelectList(countryService.GetAll(),Person.Country); 
    } 

    } 

的用法,但我觉得应该有一些办法比这两个

任何人都更加了解做到这一点的最佳方式?

回答

1

是的,nr2是最好的。

+0

其实我以为应该有比这两个更好的东西;在nr2中,我打电话给ViewModel内的数据库 – Omu 2009-11-05 14:21:47

+1

我更喜欢这样做,但大多数人不这样做。这是另一个可能会帮助你的讨论http://stackoverflow.com/questions/1593406/who-has-the-responsibilty-of-loading-data/1594300#1594300 – 2009-11-05 15:08:10

相关问题