发现 属性 未从响应主体(表单数据)绑定到模型 MVC,默认模型绑定器

Found property which wasn't bound from response body (form data) to model MVC, default model binder

我发送 post 请求并获得响应主体表单数据: 0[family]=Marco&0[name]=Polo&0[age]=66&1[family]=Family&0[name]=Name&0[age]=22

var formData = "0[family]=Marco&0[name]=Polo&0[age]=66&1[family]=Family&0[name]=Name&0[age]=22";
var data = new Dictionary<string, string>();
var preData = HttpUtility.ParseQueryString(formData);

foreach (string key in preData.AllKeys)
{
    if (key != null)
    {
        data.Add(Replace(key), preData[key]);
    }
}

我有型号:

public class User {
  public string Family {get;set;}
  public int Age {get;set;}
}

对于绑定我使用 DefaultModelBinder:

private static bool TryUpdateModel(User user, IDictionary<string, string> formdata, ModelStateDictionary modelState) where TModel : class
{
    var binder = new DefaultModelBinder();

    var valueProvider = new DictionaryValueProvider<string>(formdata, CultureInfo.InvariantCulture);

    var bindingContext = new ModelBindingContext
    {
        ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => user, typeof(User)),
        ModelState = modelState,
        PropertyFilter = propertyName => true,
        ValueProvider = valueProvider
    };

    var ctx = new ControllerContext();
    binder.BindModel(ctx, bindingContext);
    return modelState.IsValid;
}

我该怎么做?

您仍然需要在每种情况下将模型与表单数据进行比较,以便您可以尝试如下操作:

public bool HasAdditionalVals<TModel>(TModel model, IDictionary<string, string> formData)
{
    var propsNameList = new List<string>();
    var propsList = typeof(TModel).GetProperties().ToList();
    propsList.ForEach(p => propsNameList.Add(p.Name.ToLower()));

    var keysList = formdata.Keys.ToList()
    var additionalProps = keysList.Except(propsNameList);
    return additionalProps.Count() > 0;
}

然后您可以在 'TryUpdateModel' 中或任何需要检查表单数据的属性是否多于您尝试绑定的模型的地方调用它。请注意,这取决于小写形式的表单数据键。如果不是,您必须在调用 'keysList.Except(propsNameList)'.

之前确保它们是