如何使用(尝试)UpdateModel?
使用 (Try)UpdateModel 的正确方法是什么?
当我运行此命令时:
TryUpdateModel
返回 true,ViewData
没有错误,- 但我的 < code>Proxy 未更新。
操作方法
public void Save(string TypeName, int Id, FormCollection idontknow) {
var types = Assembly.GetExecutingAssembly().GetTypes();
var ObjectType=(from t in types where t.Name == TypeName select t).First();
var Proxy = context.Set(ObjectType).Find(Id); // EF 4.1
if (TryUpdateModel(Proxy, TypeName)) {
var x = ViewData.GetModelStateErrors(); // no errors
}
}
发布数据
TypeName=Thing&Id=1&Thing.Id=1&Thing.Name=hello&Thing.OptionID=2
事物类
public class Thing : Base {
public virtual Nullable<int> OptionID { get; set; }
public virtual Option Option { get; set; }
public virtual ICollection<ListItem> ListItems { get; set; }
}
public class Base {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
[NotMapped]
public virtual int? EntityState { get; set; }
}
编辑: 我还尝试显式传递表单集合 TryUpdateModel(Proxy, TypeName, idontknow)
编辑 #2: (响应 NickLarsen)
- 重新启动 VS 和服务器,没有变化。
- 值实际上位于 FormCollection 中。
- 模拟数据有效!我知道我一定在这里搞砸了一些事情。
- 使用调试器检查值。
What is the right way to use (Try)UpdateModel?
When I run this:
TryUpdateModel
returns true,ViewData
has no errors,- but my
Proxy
is not updated.
Action Method
public void Save(string TypeName, int Id, FormCollection idontknow) {
var types = Assembly.GetExecutingAssembly().GetTypes();
var ObjectType=(from t in types where t.Name == TypeName select t).First();
var Proxy = context.Set(ObjectType).Find(Id); // EF 4.1
if (TryUpdateModel(Proxy, TypeName)) {
var x = ViewData.GetModelStateErrors(); // no errors
}
}
Posted Data
TypeName=Thing&Id=1&Thing.Id=1&Thing.Name=hello&Thing.OptionID=2
Thing Class
public class Thing : Base {
public virtual Nullable<int> OptionID { get; set; }
public virtual Option Option { get; set; }
public virtual ICollection<ListItem> ListItems { get; set; }
}
public class Base {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
[NotMapped]
public virtual int? EntityState { get; set; }
}
EDIT: I also tried passing the form collection explicitlyTryUpdateModel(Proxy, TypeName, idontknow)
EDIT #2: (in response to NickLarsen)
- Restarted VS and server, no change.
- Values are actually in the FormCollection.
- Mock data works! I know I must be messing up something here.
- Using debugger to check values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我剥离了所有 EF 内容,并尝试获取该查询字符串来用值填充模型......并且它工作得很好。
老实说,我无法想象你的代码中的哪些内容会阻止它工作,但我建议你一一浏览列表,并在每一步后进行测试......
I stripped all the EF stuff and tried to get just that query string to populate the model with the values... and it worked just fine.
Honestly I can't figure think of what in your code would keep it from working, but I would suggest going through the list 1 by one and testing after each step...