0
當我更改方法EditSelectList中的組列表時,它也會影響ViewBag.Groups。爲什麼會發生?我較早分配了ViewBag。它不應該影響ViewBag.Groups和VAR tournamentsGroups變量意外更改
我有這樣的代碼在控制器:
[AllowAnonymous]
public ActionResult Details2(int id)
{
var tournamentsContext = new TournamentsContext();
var tournament = tournamentsContext.Tournament.Single(t => t.Id == id);
var groupsContext = new GroupsContext();
var tournamentsGroups = groupsContext.Groups.Where(g => g.IdTournament == tournament.Id && g.SexMale == true).ToList();
ViewBag.Groups = tournamentsGroups;
ViewBag.groupId = new SelectList(EditSelectList(tournamentsGroups), "Id", "Belt");
ViewBag.tournamentId = id;
ViewBag.InTournament = CurrentUserInTournament(tournament.Id, currentUser);
return View(tournament);
}
private List<Groups> EditSelectList(List<Groups> groups)
{
foreach (var item in groups)
{
item.Belt = item.Belt + " - " + item.WeightKg; // for dropdownlist
}
return groups;
}
,並查看
@model TournamentApp.Models.Tournament
@foreach (var item in ViewBag.Groups)
{
if ("white".Equals(@item.Belt) || true)
{
<h4>@item.Belt</h4>
}
}
// ... some another code for dropdownlist
這樣的結果是:
white - 65
white - 75
white - 85
blue - 75
但應該只是:
white
white
white
blue
'ToList()'返回一個'List'。然後你可以從幾個位置引用*('ViewBag.Groups','tournamentsGroups',以及當它傳遞給'EditSelectList')。但是仍然只有一個'List'對象。 –