简体   繁体   English

如何在控制器MVC中添加必需的模型属性?

[英]How to add required to model property in controller mvc?

I have a model CompanyInfoModel It has such field: 我有一个模型CompanyInfoModel它具有这样的字段:

[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). 在控制器中,在一定条件下的get方法中,我必须使属性CompanyName必需的(此属性并非总是必需的)。 I cannot add required property in view because of custom implementation of @Html.EditorFor . 由于@Html.EditorFor的自定义实现,因此无法在视图中添加必需的属性。

How can I add required attribute to the property in the controller? 如何在控制器的属性中添加required属性?

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 1)创建一个自定义的必填属性,并实现打开/关闭必填字段所需的逻辑

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 该模型可从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. 2)除了上述之外,您还可以实现IValidatableObject ,该对象提供了一种可以在模型绑定期间执行验证规则的方法。 Again if you can derive the validation rules wholly from the validated object. 同样,如果您可以完全从已验证的对象派生验证规则。

On your model, implement IValidatableObject 在模型上,实现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 3)如果您需要模型外部的上下文来执行验证,请在自定义模型绑定程序中进行验证,例如从DefaultModelBinder继承并重写

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!) 4)在控制器中进行操作(不推荐!)

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. 我发现用JQuery做到这一点的其他方法。 I just run 我刚跑

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

when I need it. 当我需要它时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在模型MVC 4中为我的查询linq添加自定义属性 - how to add custom property in model MVC 4 for my query linq mvc 5如果dropdownlist选择的选项比所需的其他模型属性更多 - mvc 5 if dropdownlist selected option than required different model property 如何禁用必需属性的MVC模型? - How to disable required attributes MVC model? 如何使用@ Ko.Html.Button将模型属性值发送到K-MVC中的控制器方法 - How to send model property value to controller method in K-MVC using @Ko.Html.Button 如何覆盖MVC“添加控制器” - How to override MVC "Add Controller" 将模型的IEnumerable属性传递给控制器​​post action - ASP MVC - Passing IEnumerable property of model to controller post action- ASP MVC 从Asp.Net MVC中的Controller更新模型属性 - Update Model property from Controller in Asp.Net MVC 如何将名称空间添加到Model MVC - How to add namespace into Model MVC 如何以编程方式从与 Asp.NET MVC 中控制器的模型数据绑定的表中添加\删除行 - How to add\delete rows programatically from a table that binds with model data from controller in Asp.NET MVC ASP.Net MVC:如何即时将验证添加到任何模型属性 - ASP.Net MVC: How to add validation to any model property on the fly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM