gpt4 book ai didi

asp.net-mvc - DataAnnotation 验证和自定义 ModelBinder

转载 作者:行者123 更新时间:2023-12-04 13:21:25 26 4
gpt4 key购买 nike

我一直在用 ASP.NET MVC2 进行一些实验,并遇到了一个有趣的问题。

我想围绕将用作 MVC 应用程序中的模型的对象定义一个接口(interface)。此外,我想通过使用验证属性标记此接口(interface)的成员,从而在功能上利用新的 DataAnnotation。

因此,如果我的网站有一个“照片”对象,我将定义以下接口(interface):

public interface IPhoto 
{
[Required]
string Name { get; set; }

[Required]
string Path { get; set; }
}

我将定义以下实现:
public class PhotoImpl : IPhoto 
{
public string Name { get; set; }
public string Path { get; set; }
}

我的 MVC App Controller 可能包括以下方法:
public class PhotoController : Controller
{
[HttpGet]
public ActionResult CreatePhoto()
{
return View();
}

[HttpPost]
public ActionResult CreatePhoto(IPhoto photo)
{
if(ModelState.IsValid)
{
return View();
}
else
{
return View(photo);
}

}
}

最后,为了将 PhotoImpls 绑定(bind)到这些操作方法中的参数,我可能会为 DefaultModelBinder 实现以下扩展:
public class PhotoModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if(bindingContext.ModelType == typeof(IPhoto))
{
IPhoto photo = new PhotoImpl();
// snip: set properties of photo to bound values
return photo;
}

return base.BindModel(controllerContext, bindingContext);
}
}

一切似乎都很好,除了我的 Controller 中的 ModelState.IsValid 属性似乎没有注意到 IPhoto 实现的 [Required] 属性中的无效值(例如,null)。

我怀疑我忽略了在我的 ModelBinder 实现中设置一些重要的状态。有什么提示吗?

最佳答案

我遇到过同样的问题。答案不是在您的自定义模型绑定(bind)器中覆盖 BindModel(),而是覆盖 CreateModel()...

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, System.Type modelType)
{
if (modelType == typeof(IPhoto))
{
IPhoto photo = new PhotoImpl();
// snip: set properties of photo to bound values
return photo;
}

return base.CreateModel(controllerContext, bindingContext, modelType);
}

然后,您可以让基础 BindModel 类通过验证来完成它的工作:-)

关于asp.net-mvc - DataAnnotation 验证和自定义 ModelBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2030059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com