将数据绑定到 Asp.net MVC 中的现有对象
在 ASP.Net MVC 模型绑定器中,可以创建绑定类型的对象,然后更新其属性。
例如,
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ParentType boundModel = null;
if (bindingContext.ModelType == typeof(ParentType))
{
var myFactory = new MyFactory();
var someValue = bindingContext.ValueProvider.GetValue
("someFieldId").AttemptedValue;
ChildType child = myFactory.Create(someValue);
BindModel(child);
boundModel = child;
}
return boundModel;
}
在这段代码中,我想知道是否有类似于 BindModel(child) 调用的东西,有点像来自控制器的 TryModelUpdate() ?
Within an ASP.Net MVC model binder is it possible to create an object of the bound type and then update the properties on it.
e.g.
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ParentType boundModel = null;
if (bindingContext.ModelType == typeof(ParentType))
{
var myFactory = new MyFactory();
var someValue = bindingContext.ValueProvider.GetValue
("someFieldId").AttemptedValue;
ChildType child = myFactory.Create(someValue);
BindModel(child);
boundModel = child;
}
return boundModel;
}
In this code I want to know if there is something similar to the BindModel(child) call, kind of like TryModelUpdate() from a controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为解决您的问题的更好方法是从 DefaultModelBinder 派生(我认为您可能是),然后重写 CreateModel 方法而不是 BindModel 方法。
通过从中返回您的 Child 对象,您应该沿着您正在寻找的路径前进。
I think a better approach to your problem would be to derive from the DefaultModelBinder (which I think you probably are) and then override the CreateModel method rather than the BindModel method.
By returning your Child object from that, you should be along the path you're looking for.
这个怎么样?
How about this?
绑定器只需要类属性和字段值中的名称相同,调用 updatemodel 会将任何匹配的值放入模型中。
所以你应该能够创建任一类型的类并调用 updatemodel ???
The binder simply need the same names in class properties and the field value, calling updatemodel will place any matching values into the model.
So you should be able to just create either type of class and call updatemodel ???