2015-12-23 83 views
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 
+0

'ToList()'返回一個'List'。然後你可以從幾個位置引用*('ViewBag.Groups','tournamentsGroups',以及當它傳遞給'EditSelectList')。但是仍然只有一個'List'對象。 –

回答

1

因爲ViewBag.Groups中的列表仍包含與原始列表tournamentsGroups相同的對象。對該列表的引用被複制,其內容根本不被改變。仍然只有一個列表

您需要複製整個列表及其項目,以防止後續操作更改您分配的列表。

如果您只使用一個屬性(Belt),則可能需要創建一個新的string s列表,這比克隆每個對象要容易得多。如果您需要克隆每一個對象,請查看Deep cloning objects