MVC Dropdownlistfor&LT;&GT; [英] MVC Dropdownlistfor<>
问题描述
我刚开始在MVC中的一个项目。我是新来的MVC asp.net。我想补充一个下拉列表框中不像我以前在asp.net中添加。
I just started a project in MVC. I am new to MVC asp.net. I want to add a dropdown list box like I used to add in asp.net.
<asp:Dropdownlist ID="ddlCity" runat="server">
<asp:ItemList Text="Kolkatta" Value="1"/>
<asp:ItemList Text="New Delhi" Value="2"/>
<asp:ItemList Text="Mumbai" Value="3"/>
<asp:ItemList Text="chennai" Value="4"/>
<asp:ItemList Text="Hydrabad" Value="5"/>
</asp:Dropdownlist>
我要以这种方式....意义的下拉列表框,现在我需要创建一个模型和控制器。假设我已经有一个名为员工入职表视图,我只需要在该网页上添加一个下拉列表。
我不想创建此下拉列表中的典范;我只需要在此页面上。
I want a dropdown list box in that manner.... meaning, now I need to create a model and controller for that. Suppose I have already have a view named "Employee Entry Form" and I need to add one dropdown list only on that page. I do not want to create a model for this dropdown list; I only need it on this page.
推荐答案
有关DropDownList的值应该在你的现有的视图模型:
The values for the dropdownlist should be in your existing view model:
public class WhateverViewModel
{
// All of your current viewmodel fields here
public string SelectedCity { get; set; }
public Dictionary<string, string> CityOptions { get; set; }
}
在你想要(其中SelectedCity是你的数字ID)的任何值控制器
填充这些,然后做你的看法如下:
Populate these in your controller with whatever values you want (where SelectedCity is your numerical ID), then do the following in your view:
@Html.DropDownListFor(m => m.SelectedCity,
new SelectList(Model.CityOptions, "Key", "Value", Model.SelectedCity))
如果你的价值观永远不会改变,你可以硬code他们为您的视图模型的静态
成员,然后执行:
If your values never change, you could hardcode them as a static
member of your view model and then do:
@Html.DropDownListFor(m => m.SelectedCity,
new SelectList(WhateverViewModel.CityOptions, "Key", "Value", Model.SelectedCity))
无论哪种方式,这是对这一观点的数据,因此它属于您的视图模型。如果你不使用视图模型和这一观点被直接连接到一个域实体;你应该使用它们,现在是一个很好的时间,因为任何启动。
Either way, this is data for this view, so it belongs in your view model. If you're not using view models and this view is directly tied to a domain entity; you should be using them and now is as good a time as any to start.
这篇关于MVC Dropdownlistfor&LT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!