Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating and Selecting a Drop Down List Value in ASP.NET MVC 4

Drop down lists in ASP.NET MVC confuse me. I have a model class. The model class has a string called SelectedValue. This string represents that previously selected value. I have a collection of items I've pulled from the database. Each item of the collection has an ID and a Name value. My problem is, I don't know what the recommended way of getting this information into the UI is.

I'm not sure if I should use the ViewBag or the Model. Once the value is there though, I'm not even sure what the best way to populate the UI is. I've seen HTML helpers and people using RAZOR syntax. I'm very confused. What do people recommend?

Thank you

like image 559
Eels Fan Avatar asked Mar 15 '13 19:03

Eels Fan


People also ask

How Show DropDownList with selected value from database in asp net?

You have to use SelectedValue property of DropDownList . DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.


1 Answers

This is how i do it, lets say you have 2 models Team and Player:

Player.cs

public class Player
{
    [HiddenInput(DisplayValue = false)]
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }        

    [Required]
    [ForeignKey("Team")]
    [Display(Name = "Team")]
    public int TeamId { get; set; }        

    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Display(Name = "Last name")]
    public string LastName { get; set; }

    public virtual Team Team { get; set; }        
}

Team.cs

 public class Team
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int TeamId { get; set; }

    [Display(Name = "Full Name:")]
    public string Name { get; set; }        

    public virtual ICollection<Player> Players { get; set; }
}

Then in your PlayerController: Note: team need to exist to create a player

    private void PopulateTeamsDropDownList(object selectedTeams = null)
    {
        var teamsQuery = from d in _dataSource.Teams
                         orderby d.Name
                         select d;
        ViewBag.TeamID = new SelectList(teamsQuery, "TeamId", "Name", selectedTeams);
    }

    [HttpGet]
    public ActionResult Create()
    {
        PopulateTeamsDropDownList();
        return View();
    }

    [HttpPost]
    public ActionResult Create(Player model)
    {
        if (ModelState.IsValid)
        {
            using (EFootballDb db = new EFootballDb())
            {
                try
                {
                    var player = new Player
                                     {
                                         FirstName = model.FirstName,
                                         LastName = model.LastName
                                     };
                    db.Players.Add(player);
                    db.SaveChanges();
                    return RedirectToAction("About", "Home");
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
        }
        PopulateTeamsDropDownList(model.TeamId);
        return View(model);
    }

And lastly your Create View for Player would look like this:

@{
ViewBag.Title = "Create";
 }

<h2>Create</h2>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Player</legend>

    <div class="editor-label">
            @Html.LabelFor(model => model.TeamId, "Pick Your Team")
    </div>
    <div class="editor-field">
        @Html.DropDownList("TeamId", String.Empty)
        @Html.ValidationMessageFor(model => model.TeamId)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>        

    <p>
        <input type="submit" value="Create" />
    </p>
  </fieldset>
 }

 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>

 @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
like image 131
Komengem Avatar answered Oct 12 '22 23:10

Komengem