ASP.NET MVC validation for column that's not in database
So I have following table in my database:
Account [Id (PK, int), Name(string), Password(string)]
I use an ADO.NET Entity Data Model (.edmx) and an ADO.NET Self-Tracking Entity Generator to automaticly generate my models.
I want to create an Account/Create page for users to create a new account on my website. Obviously, I want to have both a password field and a confirmPassword field to validate the user input. I have following validation model 开发者_StackOverflowto pull this off:
namespace MD5DatabaseTest.Models
{
[MetadataType(typeof(AccountMetaData))]
public partial class Account {}
public class AccountMetaData
{
public int Id { get; set; }
[Required(ErrorMessage = "Please type a username")]
public String Name{ get; set; }
[Required(ErrorMessage = "Please type a password")]
public String Password { get; set; }
[Required(ErrorMessage = "Please confirm your password")]
[Compare("Password", ErrorMessage = "Passwords do not match")]
public String ConfirmPassword{ get; set; }
}
}
Since my Database doesn't have a ConfirmPassword column my Create.cshtml code obviously fails here:
<div class="editor-label">
Confirm your password
</div>
<div class="editor-field">
@Html.Password("ConfirmPassword")
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
It is possible to validate this using the MVC 3 Data Annotions? Or do I have to write a seperate Jscript function for (client-side) validation?
Model != ViewModel.
You shouldn't use your model objects directly in your views. Create a ViewModel specific for your account creation page (one with a ConfirmPassword property like the one you have in your question) and in the Create
controller function copy the values from the ViewModel over to your domain model (which doesn't have the ConfirmPassword property) and save it.
Since my Database doesn't have a ConfirmPassword column my Create.cshtml code obviously fails
There's no reason that code should fail.
If you have validation attributes on your ViewModel, they will be respected, they don't have to be linked with a field in the database.
Actually MVC is all about seperation of concerns. The view doesn't have to know anything about the database, only about the model. And the model in turn knows about the database, but that doesn't mean it has to have a 1 on 1 mapping with that database.
I hope my explanation is a bit clear. Let me know if not, and I'll try to elaborate.
As Model != ViewModel, even if you want to use as Model, you can try;
[NotMapped]
attribute for your "ConfirmPassword" property. On your view, you can put manually your ConfirmPassword block. Not pretty, but it will work as you expected.
精彩评论