使用实体框架在 asp.net MVC 3 中进行服务器端验证

发布于 2024-12-10 14:25:10 字数 336 浏览 0 评论 0原文

我正在使用带有实体框架字的 asp.net MVC3。两者都通过 WCF Web 服务进行通信。

问题是,在服务器端数据库开发人员不想将 [Required]/[Range] 属性设置为实体类中的属性。但我想在 mvc3 应用程序中验证我的字段。我在其中添加了 WCF Web 服务参考。生成代理。

我不想按照客户端策略使用 Jquery/javascript。所以我需要在我的控制器/模型级别执行此操作。如何管理这个?一些我需要如何从 mvc 3 aaplication 动态地将所需的属性添加到每个实体的属性中。需要正确的方向来加速。

忘记添加:数据库开发人员严格避免用户要求。实体和映射中也未生成数据库。

I am using asp.net MVC3 with Enitity frameword. both are communicating via WCF web service.

the problem is that , at the server side DB developers don't want to set the [Required]/[Range] attributes to property in there Entity classes. But i want to validate the field at my end in mvc3 application. where as i added the WCF webservice reference. which generated proxy.

I don't want to use Jquery/javascript as per client policy. so i need to do it at my controller/Model level. how to manage this ? some how i need to add the required attribute to the properties of each entity dynamically from mvc 3 aaplication. need right direction to speed up.

Forgot to add: Db developer striclty avoiding to user required. also db not generated in entity and mappings.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

祁梦 2024-12-17 14:25:10

您必须 编写代码来验证您的实体。即使开发人员在实体上使用这些属性,您也不会拥有它们,因为您是通过 WCF 生成的代理访问 DAL,并且这些属性不是由您这边的工具生成的。

通过添加服务引用生成的所有类都应该是部分的,以便您可以添加自定义部分部分并实现验证(通过实现 IValidatableObject 接口)。

You must write a code to validate your entities. Even if developers used those attributes on entities you would not have them on your side because you are accessing the DAL through WCF generated proxy and those attributes are not generated by the tool on your side.

All classes generated by add service reference should be partial so you can add your custom partial part and implement validation (by implementing IValidatableObject interface).

待"谢繁草 2024-12-17 14:25:10

我同意 Ladislav Mrnka 的观点,但如果您无法更改实体类的属性,则必须将其获取:

[MetadataType(typeof(YourOwnClassForValidation))]
public partial class ClassOfYourDbDeveloper
{
    // db developer doesn't allow you to change this
    public string Title { get; set; }
}

public class YourOwnClassForValidation
{
    // here you can use your data annotations
    // important to use object
    [Required]
    public object Title { get; set; }
}

它只是用于设置属性,请在底部阅读更多相关信息:http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs

I agree with Ladislav Mrnka but if you are not able to change the properties of the entity class, you have to source it out:

[MetadataType(typeof(YourOwnClassForValidation))]
public partial class ClassOfYourDbDeveloper
{
    // db developer doesn't allow you to change this
    public string Title { get; set; }
}

public class YourOwnClassForValidation
{
    // here you can use your data annotations
    // important to use object
    [Required]
    public object Title { get; set; }
}

It's just for setting the properties, read more about that here at the bottom: http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs

榆西 2024-12-17 14:25:10

您可以注册一个类用作模型的元数据/验证提供程序。

拥有无法更改的实体:

public class MyModel 
{
    public int IntProperty { get; set; }

    public DateTime DateProperty { get; set; }
}

您可以在 MVC 端拥有它的元数据,您可以验证并提供元数据,就好像它是原始类一样:

[ValidationAttribute(...)]
[ValidationAttribute(...)]
public class MyModelValidator
{
    [Required]
    [Display("My Integer")]
    public int IntProperty { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime DateProperty { get; set; }
}

最后您只需将元数据/验证器类附加到相应的基类,例如在 Global.asax 上:

protected void Application_Start()
{
    AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;

    typeDescriptionProvider = new AssociatedMetadataTypeTypeDescriptionProvider(
            typeof(MyModel),
            typeof(MyModelValidator));

    TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, typeof(MyModel));

    // register other metadata classes
}

您可以对每个您想要的实体执行此操作。

You can register a class to be used as metadata/validation provider for your models.

Having your entity, that cannot be changed:

public class MyModel 
{
    public int IntProperty { get; set; }

    public DateTime DateProperty { get; set; }
}

You can have it's metadata on MVC side, that you can validate and provide metadata as if it is the original class:

[ValidationAttribute(...)]
[ValidationAttribute(...)]
public class MyModelValidator
{
    [Required]
    [Display("My Integer")]
    public int IntProperty { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime DateProperty { get; set; }
}

Finally you just have to attach the Metadata/Validator class to the correspondent base class, for example on Global.asax:

protected void Application_Start()
{
    AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;

    typeDescriptionProvider = new AssociatedMetadataTypeTypeDescriptionProvider(
            typeof(MyModel),
            typeof(MyModelValidator));

    TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, typeof(MyModel));

    // register other metadata classes
}

You can do this for every Entity you want.

倾`听者〃 2024-12-17 14:25:10

使用视图模型。它们的预期目的之一是从视图中抽象出模型(如 MVC 中的 M)对象。

将验证属性放入视图模型中,并使用映射器(如自动映射器)将信息复制到数据库实体或从数据库实体复制信息。

在控制器操作中使用 ModelState.IsValid 来检查视图模型是否有效。

我的 POST 操作方法通常看起来像这样:

[HttpPost]
public virtual ActionResult Edit(EditModel model)
{
    if (!ModelState.IsValid)
        return View(model);

    try
    {
        // fetch db entity
        var template = _templateService.Get(model.Id);

        // copy info from view model to db entity
        Mapper.Map(model, template);

        // save db entity
        templateService.Save(template);

        return RedirectToAction("Details", new { id = template.Id });
    }
    catch (Exception err)
    {
        Logger.Error("Failed to save template", err);
        ModelState.AddModelError("", err);
        return View(model);
    }
}

Use view models. One of their intended purposes is to abstract away model (as M in MVC) objects from the views.

Put validation attributes in your view models and use a mapper (like automapper) to copy information to/from the db entities.

Use ModelState.IsValid in your controller actions to check if the view models are valid.

My POST action methods usually look someting liek this:

[HttpPost]
public virtual ActionResult Edit(EditModel model)
{
    if (!ModelState.IsValid)
        return View(model);

    try
    {
        // fetch db entity
        var template = _templateService.Get(model.Id);

        // copy info from view model to db entity
        Mapper.Map(model, template);

        // save db entity
        templateService.Save(template);

        return RedirectToAction("Details", new { id = template.Id });
    }
    catch (Exception err)
    {
        Logger.Error("Failed to save template", err);
        ModelState.AddModelError("", err);
        return View(model);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文