Telerik UI for ASP.NET MVC 使用带整数的 CheckBox

Telerik UI for ASP.NET MVC using CheckBox with Integer

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

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

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

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 ...
}

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

有没有更简单的方法来获得这个 运行? (不更改数据库,因为它被另一个应用程序使用)

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

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

应该是:

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

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

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

You can actually control the order by implementing IContractResolver or >overriding the DefaultContractResolver's CreateProperties method.

Here's an example of my simple implementation of IContractResolver which orders the properties alphabetically:

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();
    }
}

And then set the settings and serialize the object, and the JSON fields will be in alphabetical order:

var settings = new JsonSerializerSettings()
{
    ContractResolver = new OrderedContractResolver()
};

var json = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);