我正在尝试在.NET Core中实现一些中间件,它将小数位数舍入为2位小数。所有其他映射都可以通过ComplexTypeModelBinder
正常工作。我已经尝试过在我之前调用该绑定器或继承它,但它最终会导致模型在触及控制器时为空。
基本上我的功能与此处要求的相同:Call Default Model Binder from a Custom Model Binder?,但对于.NET核心。
答案 0 :(得分:0)
public class JqGridModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var request = bindingContext?.ActionContext?.HttpContext?.Request;
var param = new JqGridParam
{
isSearch = bool.Parse(request.Query["_search"]),
pageIndex = int.Parse(request.Query["page"]),
pageSize = int.Parse(request.Query["rows"]),
sortColumn = request.Query["sidx"].ToString(),
sortOrder = request.Query["sord"].ToString(),
id = request.Query["id"].ToString(),
param = request.Query["oper"].ToString(),
editOper = request.Query["edit"].ToString(),
addOper = request.Query["add"].ToString(),
delOper = request.Query["del"].ToString(),
@where = JqGridFilter.Create(request.Query["filters"]),
//operation = (OPERATION)System.Enum.Parse(typeof(OPERATION), request.Query["oper"]=="null" ? "none": request.Query["oper"].ToString())
};
bindingContext.Result = ModelBindingResult.Success(param);
return Task.CompletedTask;
}
}
答案 1 :(得分:0)
public enum OPERATION
{
none,
add,
del,
edit,
excel
}
[ModelBinder(BinderType = typeof(JqGridModelBinder))]
public class JqGridParam
{
[BindRequired]
public int pageIndex { get; set; }
[BindRequired]
public int pageSize { get; set; }
[BindRequired]
public string sortColumn { get; set; }
[BindRequired]
public string sortOrder { get; set; }
[BindRequired]
public bool isSearch { get; set; }
[BindRequired]
public string id { get; set; }
[BindRequired]
public string param { get; set; }
[BindRequired]
public string editOper { get; set; }
[BindRequired]
public string addOper { get; set; }
[BindRequired]
public string delOper { get; set; }
[BindRequired]
public JqGridFilter where { get; set; }
[BindRequired]
public OPERATION operation { get; set; }
}
[DataContract]
public class JqGridFilter
{
[DataMember]
public string groupOp { get; set; }
[DataMember]
public Rule[] rules { get; set; }
public static JqGridFilter Create(string jsonData)
{
try
{
var serializer = new DataContractJsonSerializer(typeof(JqGridFilter));
//System.IO.StringReader reader = new System.IO.StringReader(jsonData);
System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Default.GetBytes(jsonData));
return serializer.ReadObject(ms) as JqGridFilter;
}
catch
{
return null;
}
}
}
[DataContract]
public class Rule
{
[DataMember]
public string field { get; set; }
[DataMember]
public string op { get; set; }
[DataMember]
public string data { get; set; }
}