I am trying to populate a dropdownlistfor in my view and I don't know the correct lambda expression for it to work. See code below:
@model Website.Models.modelTeamSelect
<h2>MatchSelect.cshtml</h2>
@using (Ajax.BeginForm("_PartialTeams",
new
{
model = this.Model
},
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "divMatchScheduler",
InsertionMode = InsertionMode.Replace
}))
{
<div id="divMatchScheduler">
@Html.LabelFor(m => m.modelMatch.HomeTeam)
@Html.DropDownListFor(m => m.modelMatch.HomeTeam, new SelectList
{
Items = Model.teams.Select(t => t.TeamName)
})
@Html.LabelFor(m => m.modelMatch.AwayTeam)
@Html.LabelFor(m => m.modelMatch.MatchDate)
@Html.TextBoxFor(m => m.modelMatch.MatchDate)
</div>
<input type="submit" value="Add Match" name="btnSubmit" />
}
This syntax is wrong
@Html.DropDownListFor(m => m.modelMatch.HomeTeam, new SelectList
{
Items = Model.teams.Select(t => t.TeamName)
})
My model being used by the view and the collection it contains
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Website.Models
{
public class modelMatch
{
public Guid MatchID { get; set; }
public Guid AwayTeamID { get; set; }
public string AwayTeam { get; set; }
public Guid HomeTeamID { get; set; }
public string HomeTeam { get; set; }
public DateTime MatchDate { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Website.Models
{
public class modelTeamSelect
{
public modelTeamSelect()
{
teams = new List<modelTeam>();
team = new modelTeam();
modelMatch = new Models.modelMatch();
modelMatches = new List<modelMatch>();
}
public List<modelTeam> teams { get; set; }
public modelTeam team { get; set; }
public modelMatch modelMatch { get; set; }
public List<modelMatch> modelMatches { get; set; }
public string message { get; set; }
}
}
Summary
How do I populate dropdownlistfor using a list collection that is in my model?
For most cases you'll want to use this overload of SelectList
to populate your dropdowns.
@Html.DropDownListFor(m => m.modelMatch.HomeTeam, new SelectList(Model.teams, "dataValueField", "dataTextField"))
dataValueField
and dataTextField
are the properties from your modelTeam
model that will be used as value and text for the dropdown.