简体   繁体   中英

How to add required to model property in controller mvc?

I have a model CompanyInfoModel It has such field:

[Display(Name = "CompanyName", ResourceType = typeof(i18n))]
[StringLength(64, ErrorMessageResourceType = typeof(i18n), ErrorMessageResourceName = "InvalidCompanyLength")]
public string CompanyName { get; set; }

In controller, in a get method under certain condition I must make property CompanyName required (This property is not always required). I cannot add required property in view because of custom implementation of @Html.EditorFor .

How can I add required attribute to the property in the controller?

For conditional validation You have a few options here

1) Create a custom required attribute, and implement the logic that is required to turn required field on / off

public class CustomRequiredAttribute : RequiredAttribute
{
    public override IsValid(object val, ValidationContext context)
    {
        if(SomeConditionisValid())
             return base.IsValid(val, context);
        else
             return true; // the field is valid (e.g not required)
    }
}

This can be used to drive the validation if the rules can be derived from the model. The model will be available from ValidationContext.ObjectInstance

2) Instead of the above you can implement IValidatableObject which provides a method you can implement to perform validation rules during model binding. Again if you can derive the validation rules wholly from the validated object.

On your model, implement IValidatableObject

IEnumerable<ValidationResult> Validate(
    ValidationContext validationContext
     if(SomethingIsInvalid())
         yield return new ValidationResult("Something is invalid") { }
)

3) If you need context from outside of the model to perform validation, Do the validation in a custom model binder, eg inherit from DefaultModelBinder and override

protected virtual bool OnPropertyValidating(
    ControllerContext controllerContext,
    ModelBindingContext bindingContext,
    PropertyDescriptor propertyDescriptor,
    Object value
)
{
    if(SomethingIsInvalid())
    {
         bindingContext.ModelState.AddModelError("Field", "Is Required");
    }

    base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor)
} 

Then register the model binder for the type

[ModelBinder(typeof(CompanyInfoModelBinder))]
public class CompanyInfoModel
{

}   

4) Do it in the controller (not recommended!)

Use a view model:

public class CompanyInfoViewModel {
    [Required]
    public string CompanyName { get; set; }
}

Add whatever other info you need in that view model, and either use the view model as the parameter type for your post action or create a custom model binder that will map the view model back to the domain model.

I have found other way of doing this with JQuery. I just run

$("#CompanyName").prop('required',true);

when I need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM