【问题标题】:Telerik UI for ASP.NET MVC using CheckBox with IntegerTelerik UI for ASP.NET MVC 使用 CheckBox 和 Integer
【发布时间】:2016-02-12 16:38:17
【问题描述】:

使用 Telerik DataAccess,我的数据库中有一个名为 chkSomething 的 Numeric(1,0) 字段,它在历史上用于确定复选框的状态(你知道,三态)

0 - Unchecked
1 - Checked
2 - Neither Checked nor Unchecked

但是 Kendo 复选框只是一个 2-State 复选框。所以我想我可以扩展模型:

public partial class TripleCheckboxModel
{
  private int _ID;
  public int ID { 
  get { return this._ID; }
  set { this._ID = value; } 
  }      
  private int _chkSomething;
  public int ChkSomething { 
  get { return this._chkSomething; }
  set { this._chkSomething = value; } 
  }

  [NotMapped]
  public bool BoolChkSomething { 
    get { return (this.ChkSomething == 1); }
    set { this._chkSomething = (value) ? 1 : 0; }
  }
}

在客户端完美运行:

@(Html.Kendo().CheckBoxFor(m => m.BoolChkSomething)

但是,在像这样切换复选框后调用 CRUD 操作时:

public ActionResult chk_Update([DataSourceRequest] DataSourceRequest request, TripleCheckboxModel updateItem)
{
    TripleCheckboxModel originalItem = this.dbContext.TripleCheckboxModels.FirstOrDefault(q => q.ID == updateItem.ID);

    // Here you can see the Issus
    originalItem.BoolChkSomething = updateItem.BoolChkSomething;

    this.dbContext.SaveChanges();
    return ...
}

它不会返回客户端选择的实际状态,而是在加载项目时最初设置的状态。我很难跟踪这个问题,因为似乎在将 JSON 转换回 TripleCheckboxModel 时,BoolChkSomething 属性中的设置器不会被调用(或在分配 ChkSomething 属性时被覆盖)。

有没有一种(更简单的)方法可以让它运行? (不改变数据库,因为它被另一个应用程序使用)

【问题讨论】:

    标签: asp.net-mvc telerik telerik-mvc


    【解决方案1】:

    我认为您必须检查BoolChkSomething设置代码。

    set { if (value = true) { this.ChkSomething = 1; } else { this.ChkSomething = 0;} }
    

    应该是:

    set { this._chkSomething = (value) ? 1 : 0;}
    

    因为在您的代码中您没有检查value 是否为truefalse,但您将true 分配给value

    【讨论】:

    • 感谢您指出这一点,这样它就无法工作。我切换到您的语句,因为它更优雅,但不幸的是,这并不能解决问题,因为现在有些属性具有正确的值,有些则没有,这直接指向属性的分配顺序。
    【解决方案2】:

    这里描述了答案:Order of serialized fields using JSON.NET。由于反序列化以相同的顺序工作,您可以确保 NotMapped 属性最后得到解析,而不是被其他属性覆盖。这是相关的答案,可以调整以解决此问题:

    您实际上可以通过实现IContractResolver 或>覆盖DefaultContractResolverCreateProperties 方法来控制订单。

    这是我对IContractResolver 的简单实现的示例,它按字母顺序排列属性:

    public class OrderedContractResolver : DefaultContractResolver
    {
        protected override System.Collections.Generic.IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
        {
            return base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
        }
    }
    

    然后设置设置并序列化对象,JSON字段将按字母顺序排列:

    var settings = new JsonSerializerSettings()
    {
        ContractResolver = new OrderedContractResolver()
    };
    
    var json = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2017-01-09
      • 1970-01-01
      • 2016-04-04
      • 2011-01-29
      相关资源
      最近更新 更多