1

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

1 Answer 1

1

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; }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Misha: Thanks for this. How do I combine "FirstName" and "LastName" in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.