如何在ASP.NET MVC中绑定dropdownlist?
这是我的控制器:
public ActionResult Create()
{
DB db = new DB();
var t = db.Players.ToList();
MyPlayRoundHole model = new MyPlayRoundHole();
model.MyPlayers = t;
return View("Create", model);
}
在我看来:
<tr>
<td>Player Name:</td>
<td><%= Html.DropDownList("SelectedItem", Model.MyPlayers)%></td>
</tr>
并在我的模型中:
namespace Golfsys.Model
{
public class MyPlayRoundHole
{
public IList<Player> MyPlayers { get; set; }
}
}
答案 0 :(得分:1)
您可以使用SelectLists http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist_members.aspx执行此操作:
<%=Html.DropDownList("SelectedItem",new SelectList(Model.MyPlayers,"PlayerId","PlayerName",Model.MyPlayers.First().PlayerID)) %>
当然,在调用First()设置初始选定值之前,我们必须检查MyPlayers是否为空。
[更新:如何处理全名]
绑定两个属性的最佳方法可能是在Player实体上创建新属性,它将组合它们(我认为没有办法直接在SelectList上设置它,也是因为你可以重用它更好FullName你需要的地方):
public string FullName
{
get { this.FirstName + " " + this.LastName; }
}
如果您正在使用某个创建该实体的ORM,则可以将此属性放入分部类:
public partial class Player
{
public string FullName
{
get { this.FirstName + " " + this.LastName; }
}
}