I use Entity framework for creating model. I have table hierarchy where User is my base table and I have tables Lecturer and Student which have some specific data in them. Entity framework made model that it isn't suitable so I made my middle layer called modelview where I have student table which wraps all data from both user and student tables. I have made CRUD functionality for students but I only want that admin can create student with some initial password, than admin should not have option to change student password at Edit action. The problem is th开发者_Python百科at password is required field at student Create action so I set [Required] attribute to it, but at Edit I must not have password field and my ModelState.IsValid is then always false since password field in this case isn't present and therefore is null. I thought on adding hidden password field, but that would be very bad since someone could look at page source and see password value. Can I somehow once this field required and another time not required? If you have any other idea that might help please share with me.
When a user is being edited, you can put in a placeholder hidden field, with the value * (or something like that). This will satisfy the Required
attribute - you just have to make sure you don't update the password when the user is edited :)
Maybe you could randomly generate a password and not have it be required at all.
Or you could remove the requred attribute and manually check if it's present at the serverside.
if (string.IsNullOrEmpty(user.Password))
ModelState.AddModelError("Password","A password is required");
To validate clientside, if you're using jquery validation: JQuery Docs
If you have separate views for Student
addition and editing, an alternative solution would be:
Create a
StudentViewModel
class which contains all the properties required for bothStudent
addition and editing, andCreate a
StudentAdditionViewModel
class (optionally derived fromStudentViewModel
) which includes aPassword
property.
You can then use StudentAdditionViewModel
as the Add view's model, and StudentViewModel
as the edit view's model :)
精彩评论