Asp.net mvc 3 从asp.net MVC3中的模型生成DropDownList
我有一个这样的模特Asp.net mvc 3 从asp.net MVC3中的模型生成DropDownList,asp.net-mvc-3,c#-4.0,razor,html.dropdownlistfor,html-select,Asp.net Mvc 3,C# 4.0,Razor,Html.dropdownlistfor,Html Select,我有一个这样的模特 [Required] public string Username { get; set; } [Required] public string Password { get; set; } public IEnumerable<Connection> Connections { get; set; } 我想从下拉列表中选择一个包含用户名和密码的数据库 在我的控制器中,我创建了如下的连接列表 public ActionRes
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public IEnumerable<Connection> Connections { get; set; }
我想从下拉列表中选择一个包含用户名和密码的数据库
在我的控制器中,我创建了如下的连接列表
public ActionResult Create()
{
var databaseConnection = new DatabaseConnection();
databaseConnection.Connections = new List<Connection>
{
new Connection()
{
ConnectionId = 1,
Name = @"10.44.171.39\SQL2K8R2"
},
new Connection()
{
ConnectionId = 2,
Name = "TestDb"
}
};
return View(databaseConnection);
}
public ActionResult Create()
{
var databaseConnection=新的databaseConnection();
databaseConnection.Connections=新列表
{
新连接()
{
ConnectionId=1,
名称=@“10.44.171.39\SQL2K8R2”
},
新连接()
{
ConnectionId=2,
Name=“TestDb”
}
};
返回视图(数据库连接);
}
相应的观点是
<div>
<span>Select Database</span>
<p>
<select name="Section">
<option value="" selected="selected">Select Section</option>
@foreach (var item in Model.Connections)
{
<option value="@item.ConnectionId">@item.Name</option>
}
</select>
</p>
</div>
选择数据库
选择部分
@foreach(Model.Connections中的var项)
{
@项目名称
}
当我发布表单时,我得到了用户名和密码,但没有得到
连接名称和Id
任何帮助都将不胜感激
提前感谢:)像这样修改您的
<div>
<span>Select Database</span>
<p>
@Html.DropDownListFor(
m => m.Connections.ConnectionId,
new SelectList(Model.Connections, "ConnectionId", "Name"),
"Select a Connection"
)
</p>
</div>
按照您的方式执行,您的选择将被命名为“ConnectionId”,并且不会出现名称,只有ConnectionId的值。即使在下面的解决方案中也是如此,您也需要在服务器端查找名称,或者在选择时将其存储到隐藏字段中。好的,我必须将
公共连接{get;set;}
添加到我的DatabaseConnection类中,谢谢您的回复@Karthik
<div>
<span>Select Database</span>
<p>
@Html.DropDownListFor(
m => m.Connections.ConnectionId,
new SelectList(Model.Connections, "ConnectionId", "Name"),
"Select a Connection"
)
</p>
</div>
[HttpPost]
public ActionResult Create(DatabaseConnection connection)
{
//get the selected value from dropdown.
var selected=connection.Connections.ConnectionId;
//do other stuff..
return View();
}