【发布时间】:2016-05-14 04:20:38
【问题描述】:
我正在尝试改进在 MVC 模型和视图中创建 SelectList 的方式。
有人在我的代码的早期版本中评论说我对new 的使用过多。在如下所示的模型中,我确实看到在 SelectList 的定义中使用了两次 new。但是,我不知道如何编写代码,这是我在示例中看到它定义的唯一方法。有没有更好的办法?
在模型类中,我将 SelectList 值分配给 IEnumerable<StudentRoster> StudentRosters,然后可以在视图中访问它。
这就是我在视图中创建 DropDownList 的方式。
<p>Select a campus: @Html.DropDownListFor(m=>m.SelectedCampus,Model.CampusList)
这就是我在模型中定义 SelectList 的方式。
public class SampleViewModel
{
// This IEnumerable is a SelectList in the Html.BeginForm() block
public IEnumerable<SelectListItem> CampusList { get; set; }
public string SelectedCampus { get; set; }
// This list is the "table" shown in the View that the SelectList filters
public IEnumerable<StudentRoster> StudentRosters { get; set; }
}
控制器:
public ActionResult FilterableIndex(string SelectedCampus="MRA")
{
StudentRosterViewModel vm = new StudentRosterViewModel();
vm.StudentRosters = db.StudentRosters
.Where(m => m.Campus == SelectedCampus)
.ToList();
vm.SelectedCampus = SelectedCampus;
vm.CampusList = new SelectList(new List<string>
{"CRA","DRA","MRA","PRA" });
return View(vm);
}
这是正确的编码还是养成坏习惯的例子?
【问题讨论】:
-
生成
SelectList的方式没有问题,但是拥有SelectedCampus属性然后不绑定它有点毫无意义。应该只是CampusList = new SelectList(new List<string> {"CRA","DRA","MRA","PRA" });(省略最后一个参数)然后在视图中@Html.DropDownListFor(m => m.SelectedCampus, Model.CampusList) -
请注意,您的视图模型需要一个无参数构造函数,否则您的代码会在您提交表单时抛出异常。通常它是你的控制器,它应该负责填充
SelectList属性,而不是视图模型本身(在你的情况下并不那么重要,但如果你在视图模型构造函数中访问数据库,那就是它) -
这是我断开连接的地方。控制器应该如何知道我选择了什么值(通过发布表单)并相应地刷新查询?到目前为止,我看到的唯一方法是使用构造函数参数。
-
因为如果你使用我展示的代码,你绑定到你的
SelectedCampus,所以在POST方法中,SelectedCampus的值将是你选择的选项的值。 -
我必须在控制器中进行一些其他调整。谢谢 - 这是一个巧妙的技巧。然而,另一个问题仍然存在:我将构造函数代码拉回到控制器中——我被告知控制器应该尽可能薄。我正在发布修改后的代码块。虽然它“有效”,但我认为就代码的去向而言,它仍然会更好。请稍候。
标签: c# asp.net-mvc