【问题标题】:Can't seem to get IncludeProperties working on UpdateModel in ASP.NET MVC似乎无法让 IncludeProperties 在 ASP.NET MVC 中的 UpdateModel 上工作
【发布时间】:2009-07-30 05:13:31
【问题描述】:

有人遇到过这种情况吗?

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

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”可能是定义您希望从表单中包含哪些属性,类似于绑定的工作方式。如果*是*这种情况,那么我怎么能告诉它只更新某些模型属性呢?

【问题讨论】:

    标签: asp.net asp.net-mvc updatemodel


    【解决方案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 的相似之处在于它似乎为集合类型创建了新元素。

    稍后我会尝试更多地分析它。

    【讨论】:

    • 嗨,我沿着源代码走同样的路线,看看里面发生了什么(我的下拉列表有很多问题,有时不绑定,具体取决于选择列表的来源......)。你是如何在 Reflector 中做到这一点的?能够在 MVC 框架中获取一些东西的调用堆栈会很有帮助。
    猜你喜欢
    • 2011-11-30
    • 2015-09-20
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2016-07-27
    相关资源
    最近更新 更多