代码之家  ›  专栏  ›  技术社区  ›  GONeale

似乎无法获取在ASP.NET MVC中处理UpdateModel的IncludeProperties

  •  6
  • GONeale  · 技术社区  · 17 年前

    有人运气好吗?

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

    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或default,这是它目前看起来正在做的事情。

    不过,我要说的是,也许上面的场景和我的真实场景之间的唯一区别是我在一个列表中使用updateModel,所以我有效地获取了listFromDb(parentId),然后对其应用updateModel(my list,“ListPrefix”),后者按[0]、[1]等方式获取每个项。。。它起作用了,因为所有的名字都在更新,但其他的都没有。

    更新:我刚刚意识到“include properties”可能是定义希望从表单中包含哪些属性,类似于绑定的工作方式。如果是这样的话,我怎么能告诉它只更新 某些 改为模型属性?

    1 回复  |  直到 17 年前
        1
  •  1
  •   womp    17 年前

    我一直在用反射器研究这个。。。调用堆栈是:

    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与此类似,它似乎正在为集合类型创建新元素。

    我以后再分析。