我刚刚用MVC开始了一个项目。我是MVC asp.net的新手。我想添加一个下拉列表框,就像我过去在asp.net中添加的那样。
下拉列表框的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>我想要一个以这种方式下拉列表框...这意味着,现在我需要为它创建一个模型和控制器。假设我已经有一个名为"Employee Entry Form“的视图,并且我只需要在该页面上添加一个下拉列表。我不想为此下拉列表创建模型;我只需要在此页面上使用它。
发布于 2013-06-10 18:24:39
dropdownlist的值应该在现有视图模型中:
public class WhateverViewModel
{
// All of your current viewmodel fields here
public string SelectedCity { get; set; }
public Dictionary<string, string> CityOptions { get; set; }
}在控制器中使用所需的任何值填充这些值(其中SelectedCity是您的数字ID),然后在视图中执行以下操作:
@Html.DropDownListFor(m => m.SelectedCity,
new SelectList(Model.CityOptions, "Key", "Value", Model.SelectedCity))如果您的值从不更改,您可以将它们硬编码为视图模型的static成员,然后执行以下操作:
@Html.DropDownListFor(m => m.SelectedCity,
new SelectList(WhateverViewModel.CityOptions, "Key", "Value", Model.SelectedCity))无论哪种方式,这都是此视图的数据,因此它属于您的视图模型。如果您没有使用视图模型,并且此视图直接绑定到一个域实体,那么您应该使用它们,并且现在是开始使用它们的最佳时机。
发布于 2013-10-31 11:39:25
您还可以遵循另一种方法,即在一个helper类中收集所有下拉列表,并返回这些列表,每个列表都有一个静态函数。
Ex.下拉帮助器类
namespace Asko.Web.Mvc.Infrastructure.Utils
{
public static class DropdownHelper
{
public static IEnumerable<SelectListItem> GetAllCategories()
{
var categories = category.GetAll();
return categories.Select(x => new SelectListItem { Text = x.categoryName, Value = x.categoryId.ToString()}));
}
}
},这里您将在页面中使用它:
<td style="width: 150px;">
<b>Category: </b>
<br>
@Html.DropDownListFor(m => m.CategoryId, DropdownHelper.GetAllCategories())
</td>发布于 2013-06-10 16:21:50
如果你想避免使用模型,你可以简单地使用ViewBag。在您的操作中:
ViewBag.DirectorId = new SelectList(ListOfItemsToAdd, "dataValueField", "dataTextField", movie.DirectorId);在视图中:
<%= Html.DropDownList("VariableNameToPost", ViewBag.DirectorId) //for asp.net view engine %>
@Html.DropDownList("VariableNameToPost", ViewBag.DirectorId) // for razor view engine然后,接受该变量的操作将具有如下内容:
public ActionResult theAction(string VariableNameToPost){...}参考:
https://stackoverflow.com/questions/17019272
复制相似问题