6

有没有人有这运气?

如果我理解正确,请告诉我,如果我有一个简单的模型,让我们说:

public string Name { get; set; }
public string Details { get; set; }
public DateTime? Created { get; set; }

然后我执行:

var myModel = getCurrentModelFromDb(id);
UpdateModel(myModel, "ModelName", new string { "Name", "Details" });

这应该更新名称和详细信息属性吗?因为假设'created'中已经有一个来自db的日期,所以当我执行上述操作时,它似乎将我的创建日期从原始日期设置为01-01-0001。

此外,当我尝试使用以下命令明确排除该字段时:

UpdateModel(myModel, "ModelName", 
   new string { "Name", "Details" }, new string { "Created" });

它仍被设置为 01-01-0001。这是一个错误,还是我做错了什么奇怪的事情?

我实际上想要做的是更新我的模型属性,其中有相应的表单字段,但保留其余部分,这些属性是从 db fetch 单独设置的,而不是将它们设置为 null 或默认值,这是它目前的似乎在做。

不过我会说,也许上面和我的真实场景之间的唯一区别是我在列表上使用 updateModel,所以我有效地获取 listFromDb(parentId) 然后在选择的那个上应用 updateModel(myList, "ListPrefix")将每个项目按 [0]、[1] 等...它有效,因为所有名称都在更新,但其他一切都没有。

更新:我刚刚意识到“includeProperties”可能是定义您希望从表单中包含哪些属性,类似于绑定的工作方式。如果*是*这种情况,那么我怎么能告诉它只更新某些模型属性呢?

4

1 回答 1

1

我一直在使用 Reflector 研究这个......调用堆栈是:

UpdateModel()--> TryUpdateModel()--> DefaultModelBinder.BindModel()---> 要么BindComplexModel()要么BindSimpleModel()

这是反汇编BindSimpleModel()

 if (bindingContext.ModelType != typeof(string))
    {
        if (bindingContext.ModelType.IsArray)
        {
            return ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);
        }
        Type type = ExtractGenericInterface(bindingContext.ModelType, typeof(IEnumerable<>));
        if (type != null)
        {
            object o = this.CreateModel(controllerContext, bindingContext, bindingContext.ModelType);
            Type collectionType = type.GetGenericArguments()[0];
            Type destinationType = collectionType.MakeArrayType();
            object newContents = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, destinationType);
            if (typeof(ICollection<>).MakeGenericType(new Type[] { collectionType }).IsInstanceOfType(o))
            {
                CollectionHelpers.ReplaceCollection(collectionType, o, newContents);
            }
            return o;
        }
    }

很明显,正在创建新元素。不过,我不清楚这些标志的确切逻辑,我现在没有时间进一步调查它。顺便说一句,BindComplexModel 的相似之处在于它似乎为集合类型创建了新元素。

稍后我将尝试对其进行更多分析。

于 2009-07-30T18:36:22.847 回答