【问题标题】:IEumerable<> in a MVC ViewModelMVC 视图模型中的 IEumerable<>
【发布时间】:2014-08-28 11:29:58
【问题描述】:

我一直在努力更好地掌握模型和视图模型的设计。对于大多数人来说,这可能是一个愚蠢的问题。首先,这是我的模型:

public class Cities
{
    [Key]
    public int CityID { get; set; }
    public string City { get; set; }
    public int Miles { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

现在,当我在表示层中创建 ViewModel 时,我可以只使用 IEumerable 来传递我的 Cities 表中的所有记录吗:

public class CitiesViewModel
{
    public IEnumerable<Cities> Cities { get; set; }
}

然后我可以用我的控制器遍历所有记录:

    [HttpGet]
    public ActionResult List()
    {
        CitiesViewModel model = new CitiesViewModel
        {
            Cities = repository.Cities
            .OrderBy(p => p.City)
        };
        return View(model);
    }

或者,我是否应该只传递我希望我的视图可以访问的唯一数据:

public class CitiesViewModel
{
    //public IEnumerable<Cities> Cities { get; set; }

    public string City { get; set; }
    public string State { get; set; }
}

【问题讨论】:

  • 检查one.beat.consumer's answer here,它应该会给你一个想法。
  • 我认为纯粹主义者会认为后者是更好的选择,但我认为两者都可以接受。
  • 是的,视图模型应该只提供视图所需的信息。
  • @MarcosVqzdeRdz 感谢您的参考。很棒的信息!

标签: c# asp.net-mvc design-patterns mvvm viewmodel


【解决方案1】:

你可以这样做:

class CityViewModel
{
    public string City { get; set; }
    public string State{ get; set; }
}

然后:

class CitiesViewModel
{
    public IEnumerable<CityViewModel> Cities { get; set; }
}

【讨论】:

  • 我实际上更喜欢将IEnumerable&lt;&gt; 绑定到视图,而不是创建一个只包含第一个视图模型集合的类。例如@model IEnumerable&lt;CityViewModel&gt;
  • 我也是,但我不确定这是否是视图中唯一需要的信息。
【解决方案2】:

这取决于您希望在视图上显示什么。如果一个城市的详细信息使用:

public class CitiesViewModel
{


    public string City { get; set; }
    public string State { get; set; }
}

但如果您想显示引用列表,请使用:

public class CitiesViewModel
{
    public IEnumerable<Cities> Cities { get; set; }
}

【讨论】:

    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多