不属于模型的Asp.Net MVC下拉框 [英] Asp.Net MVC Handle Drop Down Boxes that are not part of the Model

查看:53
本文介绍了不属于模型的Asp.Net MVC下拉框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小表格,用户必须填写,并且由以下字段组成.

I have a small form which the user must fill in and consists of the following fields.

名称(文本) 值(文字) 组(组-是从数据库表中提取的选项列表)

Name (Text) Value (Text) Group (Group - Is a list of option pulled from a database table)

现在,此视图的模型如下所示,

Now the Model for this View looks like so,

public string Name { get; set; }
public string Value { get; set; }
public int GroupID { get; set; }

现在,视图已强力键入上述模型.

Now the view is Strongly Typed to the above model.

一个人将使用哪种方法来填充下拉列表?由于数据不包含在模型中(可以包含在模型中),我们应该使用临时/查看数据吗? HTML助手?达到此目的的理想方法是什么.

What method would one use to populate the drop down list? Since the data is not contained within the Model (It could be contained in the Model) should we be using Temp/View data? A HTML Helper? What would be the ideal way to achieve this.

推荐答案

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

NOTE: this assumes you are using MVC2.

如果我需要一个强类型的下拉菜单(在这种情况下为国家列表),则可以在ViewModel上使用2个属性.

If I ever need a strongly typed drop-down (a list of countries in this case), I use 2 properties on my ViewModel.

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

在我的操作中,我使用类似的代码将列表预转换为IEnumerable<SelectListItem>. (这假设国家/地区类别具有名称和唯一ID).

I do a pre-conversion of my list to an IEnumerable<SelectListItem> in my action using code similar to this. (This assumes a country class with a name and unique ID).

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

然后在我的强类型视图中使用:

Then in my strongly typed view, I use:

    <%= Html.DropDownListFor(model => model.CountryID, Model.Countries) %>

这很棒,因为当您发回强类型操作(返回相同的视图模型)时,CountryID将是所选国家/地区的ID.

This is great, because when you post back to a strongly typed action (receiving the same viewmodel back), the CountryID will be the ID of the selected country.

另一个好处,如果他们对验证有疑问.您需要做的就是重新填充.Countries列表,将viewmodel传递回视图,它将自动选择正确的值.

The other benefit, if they have an issue with the validation. All you need to do is repopulate the .Countries list, pass the viewmodel back into the view and it will automatically select the the correct value.

这篇关于不属于模型的Asp.Net MVC下拉框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆