开发者

ASP.NET MVC 3: unobtrusive JavaScript validation

开发者 https://www.devze.com 2023-02-14 20:48 出处:网络
There are a lot of examples on how to \"create your own model\". Mark them with DataAnnotations. Scott Guthrie explains how to validate your model when using an ORM. What I don\'t find is when your mo

There are a lot of examples on how to "create your own model". Mark them with DataAnnotations. Scott Guthrie explains how to validate your model when using an ORM. What I don't find is when your model is actually coming in from an external DLL. How do you validate it?

Example:

/* Class coming in from an third-party DLL file. */
public class Person
{
    public string Name{get;set;}
    public int Age {get;set;}
}

The solution I am thinking of: Inherit the external class and then apply [Metadat开发者_如何学JAVAaType] to the inherited class.

[Metadata(typeof(Person2_Validation))]
public class Person2:Person{}

public class Person2_Validation
{
    [Required,Stringlength(50,ErrorMessage="Name required"]
    public string Name{get;set;}

    [RegularExpression("([0-9]+)")]
    public int Age
}

Is there a better way?


You could create a model and use a Mapper (like AutoMapper or EmitMapper or ValueInjecter) to map between your objects, and validate against the mapped model.

When you need to transfer the object back you can map between your model to the recieved model.

This is very similar to a ViewModel approach in ASP.NET MVC.

So it's something like this:

Class A (the class from the DLL) Class B (your model)

You set all your annotations on B, and create whatever properties you need.

What you use is B. When you get something from the repository/source you map (copy all relevant values) A=>B and send it (let's say as a model in a View).

When you receive B back you validate it, and then map it the other way B=>A, and send it to the repository/service.

BTW: I would recommend using this approach even if model A was YOUR class.

Why use ViewModels instead of Domain Models in Views.


@Linkgoron answer is true. You are searching view model vs domain model. we need to think the model from dll is a domain model and map it to our own view model as we did even when dealing with our own repository/persistence. it is a best practice. don't worry about mapper, it will map automatically.

See this example: http://weblogs.asp.net/shijuvarghese/archive/2010/02/01/view-model-pattern-and-automapper-in-asp-net-mvc-applications.aspx

See this @Nick DeVore answer why view model instead of domain model here Why Two Classes, View Model and Domain Model?

and also

Bestpractice - Mixing View Model with Domain Model

Your issue could be one of the reason why :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号