我正在尝试在我的视图中填充下拉列表,但我不知道正确的lambda表达式是否正常工作。请参阅以下代码:
@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" />
}
此语法错误
@Html.DropDownListFor(m => m.modelMatch.HomeTeam, new SelectList
{
Items = Model.teams.Select(t => t.TeamName)
})
我的模型由视图及其包含的集合使用
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; }
}
}
摘要
如何使用我模型中的列表集合填充dropdownlist?
答案 0 :(得分:2)
对于大多数情况,您需要使用SelectList
@Html.DropDownListFor(m => m.modelMatch.HomeTeam, new SelectList(Model.teams, "dataValueField", "dataTextField"))
来填充下拉列表。
dataValueField
dataTextField
和modelTeam
是{{1}}模型中的属性,将用作下拉列表的值和文本。
答案 1 :(得分:0)
@{
<br />
ViewBag.TeamList = Model.teams.Select(t => t.TeamName);
<br />
}
<br />
@Html.DropDownListFor(m => m.modelMatch.HomeTeam, ViewBag.TeamList as SelectList)
答案 2 :(得分:0)
您还可以创建HtmlHelperExtensions类来绑定下拉列表。
public static IEnumerable<SelectListItem> ObtenerPais(this HtmlHelper helper)
{
var cnx = new dbLenorExampleEntities();
var resultado = cnx.PAIS.ToList()
.Select(e => new SelectListItem
{
Text = e.NOMBRE,
Value = Convert.ToString(e.ID_PAIS)
}).ToList();
//if (Default)
resultado.Insert(0, new SelectListItem
{
Text = "-- Seleccionar --",
Value = ""
});
return resultado;
}
使用它:
@Html.DropDownListFor(model => model.ID_ENTIDAD, Html.ObtenerPais(Default: true))
希望这有帮助