0

這裏是我的動作代碼改變字段的值不會生效

public class personnelViewModel{ 
    public Guid PKPersonelID { get; set; } 
    public string name { get; set; } 
    public string family { get; set; } 
    public int usageCount { get; set; } 
} 

var model = from personnel in DB.RFH_Personnel select new personnelViewModel 
                 { 
                  PKPersonelID = personnel.PKPersonelID, 
                  name = personnel.Name, 
                  family = personel.Family 
                 } 
freach(var item in model) 
    item.usageCount = DB.RFH_Service.Count(d => d.FKPersonelID == item.PKPersonelID); 

return View(model); 

,這是我的看法:

@model IEnumerable<RefahiWeb.Models.personnelViewModel> 
@{  
    var grid = new WebGrid(source: Model, rowsPerPage: 15, canPage: true, canSort: true); 
} 

@grid.GetHtml(tableStyle: "table tablesorter table-bordered table-hover request-status",      
       mode: WebGridPagerModes.All, 
       columns: grid.Columns(
         grid.Column("name", "name", canSort: false),       
         grid.Column("family", "family", canSort: false),  
         grid.Column("usageCount", "usageCount", canSort: false) 
       ) 
     ) 

問題是,usageCount總是被設置爲零和價值在froeach循環中設置的值不會更改usageCount的值。提前感謝任何幫助。

+0

看起來像你有一些錯字,'item.usageHistory'應該是'item.usageCount'? –

+0

這是輸入錯誤。我編輯了這個問題。 – Beginner

回答

0

你的問題是你沒有注意到model只是一個查詢。當您循環訪問model時,請更改所有內容,但返回時,您只需重新執行您的查詢由model存儲。因此,要解決這個問題,至少有2個選擇在這裏:

  • 追加ToList()model,然後一切都應該工作:

    var model = from personnel in DB.RFH_Personnel 
          select new personnelViewModel { 
                  PKPersonelID = personnel.PKPersonelID, 
                  name = personnel.Name, 
                  family = personel.Family 
                  }.ToList(); 
    
  • 分配usageCount就在這樣的查詢:

    var model = from personnel in DB.RFH_Personnel 
          select new personnelViewModel { 
                  PKPersonelID = personnel.PKPersonelID, 
                  name = personnel.Name, 
                  family = personel.Family, 
                  usageCount = DB.RFH_Service.Count(d => d.FKPersonelID == personnel.PKPersonelID) 
                  }; 
    

注意:我不知道你的View方法可以接受,但是當你追加ToList()時,你的模型將是List...,你應該考慮到這一點來相應地修改你的代碼。