ASP.NET MVC 中的下拉列表让我感到困惑。我有一个模型课。模型类有一个名为 SelectedValue 的字符串。此字符串表示先前选择的值。我有一组从数据库中提取的项目。集合的每个项目都有一个 ID 和一个 Name 值。我的问题是,我不知道将这些信息导入 UI 的推荐方法是什么。
我不确定我应该使用 ViewBag 还是 Model。但是,一旦值在那里,我什至不确定填充 UI 的最佳方式是什么。我见过 HTML 助手和使用 RAZOR 语法的人。我很困惑。人们推荐什么?
谢谢
ASP.NET MVC 中的下拉列表让我感到困惑。我有一个模型课。模型类有一个名为 SelectedValue 的字符串。此字符串表示先前选择的值。我有一组从数据库中提取的项目。集合的每个项目都有一个 ID 和一个 Name 值。我的问题是,我不知道将这些信息导入 UI 的推荐方法是什么。
我不确定我应该使用 ViewBag 还是 Model。但是,一旦值在那里,我什至不确定填充 UI 的最佳方式是什么。我见过 HTML 助手和使用 RAZOR 语法的人。我很困惑。人们推荐什么?
谢谢
我就是这样做的,假设你有 2 个模型Team and 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; }
}
团队.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; }
}
然后在你的 PlayerController 中: 注意:团队需要存在才能创建一个玩家
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);
}
最后,您的 Create View for Player 将如下所示:
@{
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")
}
我这样做的方式是让下拉列表成为我的 ViewModel 的一部分 .... 说它是 Products .... 所以在我的 ViewModel 中我有一个
public SelectList Products { get; set;}
public int ProductId { get; set; } // For the the selected Product
因此,当视图加载时,我正在填充模型以返回控制器中的视图,我会执行以下操作:
model.Products = new SelectList(MyEnumerableofProducts, "ValueField", "TextField", {value of the selected item in the dropdown, as a string)
在我看来,我会:
@Html.DropDownListFor(model => model.ProductId, Model.Products, "Please Select")
return View(model)
除了上述方法,您还可以使用此方法在查找表中使用多个外键。据我所见,它非常清晰有效。
如果您使用的是 VB.Net - MVC4- Razor 这个答案与 Frigik 几乎相同(感谢 Frigik)
在您的模型中创建两个字段,一个是保存 SelectedItem 的字段(这里是字符串的 TagType),第二个是下拉值(TagTypeList)
Imports System.Web.Mvc
Private _tagType As String
Private _tagTypeList As List(Of SelectListItem)
Public Property TagType() As String
Get
Return _tagType
End Get
Set(ByVal value As String)
_tagType = value
End Set
End Property
Public Property TagTypeList() As List(Of SelectListItem)
Get
Return _tagTypeList
End Get
Set(value As List(Of SelectListItem))
_tagTypeList = value
End Set
End Property
'In the constructor
Sub New()
TagTypeList = CommonUtility.LoadDropDownByName("TAGTYPE")
End Sub
Imports System.Web.Mvc
Imports System.Collections.Generic
Public Shared Function LoadDropDownByName(ByVal DropDownName As String) As List(Of SelectListItem)
Dim dt As DataTable
Dim ds As DataSet
Dim results As List(Of SelectListItem) = Nothing
Try
ds = objSignOn.LoadDropDown(DropDownName) 'Pass the dropdown name here and get the values from DB table which is - select ddlId, ddlDesc from <table name>
If Not ds Is Nothing Then
dt = ds.Tables(0)
If (dt.Rows.Count > 0) Then
results = (From p In dt Select New SelectListItem With {.Text = p.Item("ddlDesc").ToString(), .Value = p.Item("ddlId").ToString()}).ToList()
End If
End If
Catch ex As Exception
End Try
Return results
End Function
@Html.DropDownListFor(Function(x) x.TagType, Model.TagTypeList, "", New With {.id = "ddlTagType",.class = "dropDown", .style = "width: 140px"})
这里第三个参数(可选)为空,它将在下拉列表中插入第一个为空的项目。第一个参数是 selectedItem,一旦值已经存在于 DB 表中,它有助于填充。
希望这对使用 VB.Net 的人有所帮助