【问题标题】:Generate a DropDownList from a Model in asp.net MVC3从 asp.net MVC3 中的模型生成 DropDownList
【发布时间】:2013-02-14 05:31:46
【问题描述】:

我有一个类似的模型

  [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。

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

【问题讨论】:

  • 按照您的方式进行操作,您的选择将被命名为“ConnectionId”,并且名称不会出现,只有 ConnectionId 的值。即使在下面的解决方案中,您也需要在服务器端查找名称或将其存储到隐藏字段中。

标签: asp.net-mvc-3 c#-4.0 razor html.dropdownlistfor html-select


【解决方案1】:

像这样修改你的&lt;select&gt;

<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();
}

【讨论】:

  • 好的,我必须将 public Connection Connection { get; set; } 添加到我的 DatabaseConnection 课程中 感谢您的回复 @Karthik
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2016-09-21
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
相关资源
最近更新 更多