一种更简单的方法:将静态数据放入@Html.DropDownList

本文关键字:数据 静态 DropDownList @Html 方法 一种 更简单 | 更新日期: 2023-09-27 18:12:57

我通过将旧的PHP程序重构为ASP格式来学习c#/MVC 4。该程序的目的是为客户约会创建日历条目,包括一些基本的客户信息。我最近的挑战是将静态数据加载到多个@Html中。页面上的下拉列表。我能够通过这(如何在MVC Html.DropDownList()中添加项目的静态列表)和(我怎么能得到这个ASP。. NET MVC SelectList工作?),但我觉得我在重新发明轮子…

part OF MODEL: (commondatmodel .cs)

public class apptCounties{
  public IEnumerable<SelectItemList> Counties {get; set;}
  public apptCounties()
  {
    Counties = new[]
      {
        new SelectListItem{Text="Cook",Value="Cook"},
        new SelectListItem{Text="Dupage",Value="Dupage"},
        new SelectListItem{Text="Lake",Value="Lake"}
      };
  }
}

VIEWMODEL:(ScheduleDataViewModel.cs)

public class ScheduleDataViewModel {
  public apptClient ClientData {get; set;} 
    /* ^--This is from another model specific to this app - I'm attempting to use   
          "CommonDataModel.cs" to hold multiple lists of static data (Counties, Races, 
           Genders, etc) & then append app-specific data through specialized models. 
           I plan on expanding functionality later. */
  public apptCounties Counties {get; set;}
  public ScheduleDataViewModel()
  {
    ClientData = new apptClient(); 
    Counties = new apptCounties();
  }
}

控制器:(ScheduleController.cs)

public ActionResult Schedule()
{
  var model = new ScheduleDataViewModel();
  return View(model);
}

part OF VIEW:cshtml -强类型到ScheduleDataViewModel)

@Html.DropDownList("Counties", Model.Counties)

抱歉这里有任何混乱的语法-我的代码不在我面前!我可以验证,至少上面的一般想法在构建时是有效的&测试。

我担心我把一个本应简单得多的程序弄得过于复杂了。我在这里使用的所有构造函数方法是否都是正确的,或者有人可以提出一个更优雅的解决方案来提供静态数据列表,而不需要数据库的好处?

一种更简单的方法:将静态数据放入@Html.DropDownList

如果您的列表是静态的并且相对独立于您的实际模型,那么您可能会发现在单独的静态类中定义它们会更简单:

public static class ListOptions
{
    public static readonly List<string> Counties = ...
}

然后在视图中创建SelectList:

@Html.DropDownListFor(m => m.County, new SelectList(ListOptions.Counties))
如果合适的话,这样做并没有什么本质上的错误。如果你的列表只与那个特定的模型相关,那么是的,它属于视图模型;但是,即使这样,如果值不是可变的,我也不会担心将其简单地设置为静态属性。

我当然不同意在视图中创建SelectList本身必然是一件坏事的观点;毕竟,模型和控制器不需要知道值来自SelectList—只需要知道被选中的值。选项的呈现方式是视图的关注点。

看起来不错。也许会有一些语法上的改进。

行动

public ActionResult Schedule()
{
    return View(new ScheduleDataViewModel());
}

视图模型

// You want class names to be Upper-case
public class ScheduleDataViewModel 
{
    public ApptClient ClientData { get; set; } 
    public ApptCounties Counties { get; set; }
    public ScheduleDataViewModel()
    {
        ClientData = new ApptClient(); 
        Counties = new ApptCounties();
    }
}