Reputation: 1105
I have a model like
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public IEnumerable<Connection> Connections { get; set; }
And Connection class is
public class Connection
{
public int ConnectionId { get; set; }
public string Name { get; set; }
}
I want to select a database from a drop-down list which will have a user name and password.
In my Controller I have Created Connection list like below
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);
}
And the corresponding view is
<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>
When I am posting the form I am getting username and password Ok but not getting the
Connection Name and Id .
Any help would be appreciated Thanks in advance :)
Upvotes: 0
Views: 400
Reputation: 5545
Modify your <select>
like this
<div>
<span>Select Database</span>
<p>
@Html.DropDownListFor(
m => m.Connections.ConnectionId,
new SelectList(Model.Connections, "ConnectionId", "Name"),
"Select a Connection"
)
</p>
</div>
When you have posted your form, then it will automatically bind to the ConnectionId property.
Now add a post action to your controller.
[HttpPost]
public ActionResult Create(DatabaseConnection connection)
{
//get the selected value from dropdown.
var selected=connection.Connections.ConnectionId;
//do other stuff..
return View();
}
Upvotes: 1