我有一个类似
的模型 [Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public IEnumerable<Connection> Connections { get; set; }
Connection类是
public class Connection
{
public int ConnectionId { get; set; }
public string Name { 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);
}
相应的观点是
<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>
当我发布表单时,我收到用户名和密码确定但没有得到
连接名称和ID。
任何帮助将不胜感激 在此先感谢:)
答案 0 :(得分:1)
像这样修改<select>
<div>
<span>Select Database</span>
<p>
@Html.DropDownListFor(
m => m.Connections.ConnectionId,
new SelectList(Model.Connections, "ConnectionId", "Name"),
"Select a Connection"
)
</p>
</div>
当您发布表单后,它将自动绑定到ConnectionId属性。
现在向您的控制器添加一个帖子操作。
[HttpPost]
public ActionResult Create(DatabaseConnection connection)
{
//get the selected value from dropdown.
var selected=connection.Connections.ConnectionId;
//do other stuff..
return View();
}