我有Shop
型号:
public class Shop
{
public int ShopId { get; set; }
[Display(Name = "Winkel")]
public string Name { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
Weekday
的模型:
public class WeekDay
{
public int WeekDayId { get; set; } // Integers from 0 to 6 where Sunday is 0 and Saturday 6
// so that it maps with the DayOfWeek enumeration
[Required]
[Display(Name = "Dag")]
public string Day { get; set; }
public int? ShopId { get; set; }
public virtual Shop Shop { get; set; }
}
现在我的目标是在他们旁边显示七天的下拉列表,其中包含可供选择的商店。我希望能够显示属于当前在下拉列表中选择的Html.DropDownList(For)
中所选日期的当前商店。下一步也是最后一步是能够单击按钮并保存所有当前选定的值并更新数据库中的WeekDay
表,如下所示:
WeekDayId ShopId Day 1 NULL Zondag 2 1 Maandag 3 1 Dinsdag 4 1 Woensdag 5 1 Donderdag 6 2 Vrijdag 7 NULL Zaterdag
为此,我制作了以下ViewModel:
public class ShopWeekDayViewModel
{
public IEnumerable<Shop> ShopItems { get; set; }
public List<WeekDay> WeekDays { get; set; }
}
然后在视图中,我使用WeekDay
显示不同的Shop
,如下所示:
@model ViewModels.ShopWeekDayViewModel
<table>
@foreach (var weekDay in Model.WeekDays)
{
<tbody>
<tr>
<td>
@Html.DisplayFor(d => weekDay.Day)
</td>
<td>
@Html.DropDownListFor(m => weekDay.Shop.ShopId,
new SelectList(Model.ShopItems,
"ShopId",
"Name",
Model.ShopItems),
"")
</td>
</tr>
</tbody>
}
</table>
现在DropDownListFor
中的当前值(来自数据库 - 所以当前与工作日相关的实际商店)未被选中,我不知道如何实现这一目标。我希望有人可以帮助我。
答案 0 :(得分:3)
试试这个:
@Html.DropDownListFor(m => weekDay.Shop.ShopId,
new SelectList(Model.ShopItems,
"ShopId",
"Name",
weekDay.Shop.ShopId)
)
SelectList
构造函数的最后一个参数是object
,表示所选值。目前,您为该参数传递IEnumerable
,因为您想要选择单个值,所以没有任何意义。另请注意,我使用的是weekDay.Shop.ShopId
而不是Model.Shop.ShopId
,以便引用属于当前Shop
的{{1}}。
答案 1 :(得分:0)
您正在将SelectList
选定值设置为项目列表。
将其更改为使用不同的重载,并且具有选定的值
new SelectList(Model.ShopItems, "ShopId", "Name")
所以你看到了:
@model ViewModels.ShopWeekDayViewModel
<table>
@foreach (var weekDay in Model.WeekDays)
{
<tbody>
<tr>
<td>
@Html.DisplayFor(d => weekDay.Day)
</td>
<td>
@Html.DropDownListFor(m => weekDay.Shop.ShopId,
new SelectList(Model.ShopItems,
"ShopId",
"Name"))
</td>
</tr>
</tbody>
}
</table>