开发者

How to bind dropdownlist in ASP.NET MVC?

How to bind dropdownlist in ASP.NET MVC?

Here's my controller:

public ActionResult Create()
    {
        DB db = new DB();

        var t = db.Players.ToList();

        MyPlayRoundHole model = new MyPlayRoundHole();        
        model.MyPlayers = t;

        return View("Create", model);
    } 

and in my view:

<tr>
                    <td>Player Name:</td>
                    <td><%= Html.DropDownList("SelectedItem", Model.MyPlayers)%></td>
                </tr>

and in my Model:

namespace Golfsys.Model开发者_开发百科
{
    public class MyPlayRoundHole
    {
        public IList<Player> MyPlayers { get; set; }
    }
}


You can do it using 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)) %>

Of course you we'll have to check if MyPlayers list if empty before calling First() to set initial selected value.

[Update: How to deal with fullname]

Probably the best way to bind two properties is creating new property on Player entity that is going to combine them (I don't think there is a way to set it directly on SelectList, also it's better like this because you can reuse FullName where ever you need):

public string FullName
{
   get { this.FirstName + " " + this.LastName; }
}

If you are using some ORM that creates that entity, you can put this property into the partial class:

public partial class Player
{
    public string FullName
    {
       get { this.FirstName + " " + this.LastName; }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜