似乎无法获得在ASP.NET MVC中的UpdateModel上工作的IncludeProperties
有没有人有幸与此?似乎无法获得在ASP.NET MVC中的UpdateModel上工作的IncludeProperties
请让我知道,如果我理解正确的话,如果我有一个简单的模型假设有:
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" });
若本ONLY更新名称和详细属性? 因为我们假设在'created'中已经有了一个来自db的日期,当我这样做时,它似乎将我的创建日期从原始设置为01-01-0001。
而且,当我再尝试明确排除与此字段:
UpdateModel(myModel, "ModelName",
new string { "Name", "Details" }, new string { "Created" });
它仍然被设置为01-01-0001。这是一个错误,或者我做错了一件奇怪的事情?
我有效的想要做的是更新我的模型属性,其中有相应的表单域,但将其余的单独设置从数据库提取单独设置,而不是将它们设置为空或默认,是目前看来正在做的事情。我会说虽然,也许上面和我的现实世界的场景之间的唯一区别是我在列表上使用updateModel,所以我实际上得到listFromDb(parentId),然后应用updateModel(myList,“ListPrefix”)在那个由[0],[1]等拾取每个项目的项目上......它可以工作,因为所有的名字都在更新,但其他的都不是。
更新:我刚刚意识到可能'includeProperties'是定义您希望从表单中包含哪些属性,类似于绑定的工作方式。如果这*是这种情况,那么我怎么能告诉它只更新某些模型属性呢?
我一直在寻找这个使用反射...调用堆栈是:
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类似于它似乎正在创建集合类型的新元素。
我会尽量稍后分析它。
感谢您的帮助womp。 – GONeale 2009-08-03 23:30:19