【问题标题】:Looping through a viewmodel and updating a value in my C# MVC app循环浏览视图模型并更新我的 C# MVC 应用程序中的值
【发布时间】:2013-03-15 14:59:06
【问题描述】:

我有一个视图模型:

public class RatesViewModel
{
    public string RoomName { get; set; }
    public string TypeName { get; set; }
    public long TypeID { get; set; }
    public int TypeCount { get; set; }
    public virtual IQueryable<Occ> Occs { get; set; }

}
public class Occ
{
    public string occ { get; set; }
    public decimal ratetocharge { get; set; }
    public int numOfOcc { get; set; }
    public virtual RatesViewModel RatesViewModel { get; set; }
}

这会填充一个变量“房间”。

基于某些情况,我想更新 Occ.ratetocharge - 例如,将它们全部更改为扣除 50:

  foreach (var r in rooms)
        {
        // do a query which looks up a value from another table
        if (conditionMet == true)
        {
             r.Occs.ratetocharge = r.Occs.ratetocharge - 50;
        }
        }

然而,

r.Occs.ratetocharge

...不允许。所以我想知道如何更新ratetocharge?我的视图模型设置错误,还是有更好的方法来实现我想要实现的目标?

感谢您的建议,

标记

【问题讨论】:

  • 这只是一个 C# 问题,与 ViewModels、MVC 或实体框架无关。您只是试图修改集合的属性,如果不显式迭代集合中的每个项目,就无法完成。

标签: c# asp.net-mvc asp.net-mvc-3 linq entity-framework


【解决方案1】:

你必须做这样的事情

if (conditionMet == true)
{
    foreach(Occ occ in r.Occs)
    {
        occ.ratetocharge = occ.ratetocharge - 50;
    }
}

【讨论】:

    【解决方案2】:

    你应该使用索引号

      r.Occs[Index].ratetocharge - 50;
    

    或使用循环

    foreach (var r in rooms)
            {
            // do a query which looks up a value from another table
            if (conditionMet == true)
               {
           foreach(Occ occ in r.Occs)
               {
             occ.ratetocharge = occ.ratetocharge - 50;
               }       
              }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 2018-05-31
      相关资源
      最近更新 更多