Asp.net mvc 多个ActionResults,单个视图包含从Controller填充的DropDownList

Asp.net mvc 多个ActionResults,单个视图包含从Controller填充的DropDownList,asp.net-mvc,Asp.net Mvc,我有2个ActionResults,它们返回的视图与DropDownList源相同 Public ActionResult Create() { var model = new ViewModel { Entity = new Entity(), Categories = GetCategories() }; return View("Edit", model); } Public ActionResult Edit(int id) {

我有2个ActionResults,它们返回的视图与DropDownList源相同

Public ActionResult Create()
{
    var model = new ViewModel {
        Entity = new Entity(),
        Categories = GetCategories()
    };

    return View("Edit", model);
}

Public ActionResult Edit(int id)
{
    var model = new ViewModel {
        Entity = GetFromDatabase(id),
        Categories = GetCategories()
    };

    return View(model);
}

我觉得我打破了干涸的原则,即使我已经将类别的总体转移到了一个方法中。是否有更好的方法来处理这个问题,并且只说明从哪里获得分类?

我认为您有点担心过度了。这个代码对我来说很好。这更具可读性。只要你没有大的性能问题,你就不必担心

如果您仍然想避免
GetCategories
在两个位置调用,您可以将其放入ViewModel类的构造函数中

public class ViewModel
{
  public ViewModel()
  {
  }
  public ViewModel(bool includeCategories)
  {
    this.Categories=SomeService.GetCategories();
  }

  public List<SelectListItem> Categories { set;get;}
  //other properties
}
公共类视图模型
{
公共视图模型()
{
}
公共视图模型(bool包括类别)
{
this.Categories=SomeService.GetCategories();
}
公共列表类别{set;get;}
//其他属性
}

如何处理这件事取决于你。没有书面规定遵循您认为更具可读性且看起来更干净的内容。但就我个人而言,我会将ViewModel作为简单的POCO类,而不使用任何构造函数逻辑来加载数据。我很乐意在这两种操作方法中调用
GetCategories
。对我来说,这看起来清晰易懂。

谢谢,我想我只是需要得到一个保证,那就是我已经考虑过了。我遇到的最大问题是,如果类别是后来添加的,而我忘记在所有ViewModels中填充它们。这是一个小的细微差别,但仍然令人讨厌。