从 cookie 问题中提取的自定义模型绑定器?
我正在尝试执行以下操作。
使用默认模型绑定器从查询字符串值绑定对象。
如果失败,我会尝试从 cookie 值绑定对象。
但是,我在该对象上使用数据注释,但遇到以下问题。
- 如果没有查询字符串参数,默认模型绑定器甚至不会在必填字段上注册任何验证错误。如果属性本身不在查询字符串集合中,它显然不会触发这些验证器。我怎样才能改变这种行为?如果必填字段不在查询字符串中,我希望它们是错误的。
- 如果确实有模型验证错误,我想从 cookie 加载模型,然后重新验证对象。我不确定如何让模型绑定器验证我自己填充的对象。
这是我到目前为止所拥有的。
public class MyCarBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var myCar = base.BindModel(controllerContext, bindingContext);
if (!bindingContext.ModelState.IsValid)
{
myCar = MyCar.LoadFromCookie();
// Not sure what to do to revalidate
}
return myCar;
}
}
任何有关如何正确执行此操作的帮助将不胜感激。
I am trying to do the following.
Use the default model binder to bind an object from query string values.
If that fails, I then try and bind the object from cookie values.
However I am using dataannotations on this object and I am having the following problems.
- If there are no querystring parameters the default model binder doesn't even register any validation errors on required fields. It apparently doesn't even fire these validators if the property itself is not in the query string collection. How can I change this behavior? I would like the required fields to be errors if they aren't in the query string.
- If I do have model validation errors, I would like to then load the model from the cookie and then revalidate the object. I am not sure how to get the model binder to validate an object I have populated myself.
Here is what I have so far.
public class MyCarBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var myCar = base.BindModel(controllerContext, bindingContext);
if (!bindingContext.ModelState.IsValid)
{
myCar = MyCar.LoadFromCookie();
// Not sure what to do to revalidate
}
return myCar;
}
}
Any help on how to properly do this would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,我自己解决了。在此发布解决方案,以防有人有意见或可能想使用它。
Well, I solved it myself. Posting the solution here in case anyone has a comments or might like to use it.