0

我有一个模型

  [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }

    public IEnumerable<Connection> Connections { get; set; }

连接类是

 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 。

任何帮助将不胜感激在此先感谢:)

4

1 回答 1

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();
}
于 2013-02-28T06:17:12.043 回答