Asp.Net MVC如何处理不属于模型的下拉框

4
我有一个小表单,用户必须填写,包括以下字段。
名称(文本) 值(文本) 组(组 - 是从数据库表中获取的选项列表)
现在,该视图的模型如下所示:
public string Name { get; set; }
public string Value { get; set; }
public int GroupID { get; set; }

现在视图已经强类型化到上面的模型了。
要填充下拉列表,应该使用什么方法?由于数据不包含在模型中(虽然它可以包含在模型中),所以我们应该使用Temp/View数据吗?一个HTML Helper?最理想的方式是什么?
3个回答

3

我使用一个ViewModel,并且其中包含一个字典(我喜欢MVC Contrib的选择框),其中包含所有属性,类似于:

class LeViewModel {
    public string Name { get; set; }
    public string Value { get; set; }
    public int GroupID { get; set; }
    public Dictionary<string, string> Groups {get; set;}
}

那么在你的视角中,你只需要做

<%: Html.Select(m => m.GroupId).Options(Model.Groups) %>

希望能对您有所帮助。

2

注意:这假设您正在使用MVC2。

如果我需要一个强类型的下拉列表(在这种情况下是国家列表),我会在我的ViewModel上使用两个属性。

    public IEnumerable<SelectListItem> Countries { get; set; }
    public int CountryID { get; set; }

我在我的操作中对列表进行了预转换,使用类似于以下代码的代码将其转换为 IEnumerable<SelectListItem>。(这假设一个包含名称和唯一ID的国家类)。

        viewModel.Countries = Repository.ListAll().Select(c => new SelectListItem { Text = c.Name, Value = c.ID }); 

然后在我的强类型视图中,我使用以下代码:
    <%= Html.DropDownListFor(model => model.CountryID, Model.Countries) %>

这很好,因为当你返回到一个强类型的操作(接收相同的视图模型)时,CountryID 将是所选国家的 ID。
另一个好处是,如果他们有验证问题,你只需要重新填充 .Countries 列表,将视图模型传回视图,它就会自动选择正确的值。

pitts - 这个操作失败并显示以下错误信息:"具有键 'OptionGroupID' 的 ViewData 项的类型为 'System.Int32',但必须是 'IEnumerable<SelectListItem>' 类型。" 使用以下语法:<%= Html.DropDownListFor(model => model.OptionGroupID, Model.OptionGroups) %> - LiamB
@Pino,这真的很奇怪。让我明天在工作时检查我的代码,然后回复你。 - Alastair Pitts
pitts - 我在传递一些数据时犯了一个错误。这个方法很有效。谢谢。 - LiamB

1
我喜欢以下的方法:拥有一个帮助类来替你执行这些事情,就像这样(伪代码):
class DropdownLogic { 
    public DropdownLogic(MyModel model) { /* blah */ }

    public ListOfDropdownItems ToDropdown() { 
        /* do something with model and transform the items into items for the dropdownlist */
       // f.e. set the item that matches model.GroupId already as selected
    }
 }

在你的模型中添加:

 public DropdownLogic Groups { get; set; }

而在你的观点中:

<%=Html.Dropdown(Model.Groups.ToDropdown())%>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接