我试图理解为什么我的Html.ListBoxFor()
在加载视图时没有突出显示当前所选项目。
我有一个数据库模型:
public class Issue
{
[Key]
public int IssueId { get; set; }
public int Number { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public virtual ICollection<Creator> Creators { get; set; }
}
public class Creator
{
[Key]
public int CreatorId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
}
public class Icbd : DbContext
{
public DbSet<Issue> Issues { get; set; }
public DbSet<Creator> Creators { get; set; }
}
然后我有一个编辑模型:
public class IssueEditModel
{
public Issue Issue { get; set; }
public IEnumerable<Creator> Creators { get; set; }
public IEnumerable<Creator> SelectedCreators { get {return Issue.Creators;} }
}
然后,在我的控制器中,我填充IssueEditModel
:
public ActionResult EditIssue( int id = 0 )
{
IssueEditModel issueEdit = new IssueEditModel{
Creators = db.Creators.ToList(),
Issue = new Issue{ Creators = new List<Creator>()},
};
if (id > 0)
{
issueEdit.Issue = db.Issues.Include("Creators").Where(x => x.IssueId == id).Single();
}
return View(issueEdit);
}
这会正确填充所有对象(据我所知,无论如何。)在我的视图中,我正在编写一个这样的列表框:
<%: Html.ListBoxFor(
x => x.SelectedCreators,
new SelectList(
Model.Creators,
"CreatorId",
"LastName"
)
)%>
这会正确列出所有选项,但我无法获取要突出显示的当前选择项目。我几乎想编写自己的Html Helper,因为这是一个如此简单的操作,我不明白为什么这么困难。
为什么Html Helper不会突出显示当前项目?
答案 0 :(得分:3)
您需要一个标量类型列表作为ListBoxFor
助手的第一个参数,它将映射到您想要预选的创建者ID:
public class IssueEditModel
{
public IEnumerable<Creator> Creators { get; set; }
public IEnumerable<int> SelectedCreatorIds { get; set; }
}
然后:
IssueEditModel issueEdit = new IssueEditModel
{
Creators = db.Creators,
SelectedCreatorIds = db.Creators.Select(x => x.CreatorId)
};
并在视图中:
<%: Html.ListBoxFor(
x => x.SelectedCreatorIds,
new SelectList(
Model.Creators,
"CreatorId",
"LastName"
)
) %>
答案 1 :(得分:1)
Darin提交的示例几乎是正确的,但存在轻微错误。目前,他的例子将预选所有创作者!但是,期望的结果是仅预先选择与特定问题实例相关联的创建者。
所以这个:
IssueEditModel issueEdit = new IssueEditModel
{
Creators = db.Creators,
SelectedCreatorIds = db.Creators.Select(x => x.CreatorId)
};
应该是这样的:
IssueEditModel issueEdit = new IssueEditModel
{
Creators = db.Creators,
SelectedCreatorIds = CurrentIssue.Creators.Select(x => x.CreatorId)
};
CurrentIssue 是问题类的实例化(可能以前是从数据存储区填充的)。