tjans
tjans

Reputation: 1554

Conditional required data annotation with EditorForModel

We have a ViewModel for "create" and one for "edit." The edit inherits from create so that we're sharing common fields. We are then using an @Html.EditorForModel("User") that uses the "create" as its model.

This is for editing users, so I need the password field to be required on create, but not required on delete. Thus, the create VM has Password with [Required] decorating it, while the edit VM has password property with no decoration, and is also declared with new (public new string Password {get;set;}).

This is almost exactly similar to this question: MVC4 Conditional Required Annotation

For my situation, it's still requiring the field I believe due to the EditorTemplate using the create object as its model instead of the edit. I tried changing it from editorformodel to:

@Html.EditorFor(model=>model, "User")

in hopes that because edit is actually a "create" due to inheritance that it would work, but it'still barking at me for not providing the required field when I post.

Is there a way to accomplish what I'm attempting, or are my options to either remove the required and handle it server-side, or split the editor template into two templates?

Upvotes: 0

Views: 370

Answers (1)

Gjohn
Gjohn

Reputation: 1281

You can create a custom attribute to drive your check on whether the password is required or not. When the submission happens to the server your custom attribute can check to see if the you are dealing with an Update or and Insert and then invalidate the model if it needs to.

Here are some resources on creating custom attributes and custom attributes with unobstrusive jquery validation

Happy Coding!!

Upvotes: 1

Related Questions