Changing validation range programmatically (MVC3 ASP.NET)

后端 未结 2 1448
我在风中等你
我在风中等你 2021-01-04 10:40

Let\'s say I have this view model:


    public class MyModel
    {
        [Range(0, 999, ErrorMessage = \"Invalid quantity\")]
        public int Quantity { get;         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 11:28

    I think your best bet might be to implement a custom model binder for your specific Model (MyModel). What you could have is something like this:

    public class MyModel
    {
        public int Quantity { get; set; }
    } // unchanged Model
    
    public class MyViewModel
    {
        public MyModel myModel { get; set; }
        public int QuantityMin { get; set; }
        public int QuantityMax { get; set; }
    }
    

    Then you can set these values, and in your custom model binder you can compare your myModel.Quantity property to the QuantityMin and QuantityMax properties.


    Example

    Model:

    public class QuantityModel
    {
        public int Quantity { get; set; }
    }
    

    ViewMode:

    public class QuantityViewModel
    {
        public QuantityModel quantityModel { get; set; }
        public int QuantityMin { get; set; }
        public int QuantityMax { get; set; }
    }
    

    Custom Model Binder:

    public class VarQuantity : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            int MinValue = Convert.ToInt32(bindingContext.ValueProvider.GetValue("QuantityMin").AttemptedValue);
            int MaxValue = Convert.ToInt32(bindingContext.ValueProvider.GetValue("QuantityMax").AttemptedValue);
            int QuantityValue = Convert.ToInt32(bindingContext.ValueProvider.GetValue("quantityModel.Quantity").AttemptedValue);
    
            if (!(QuantityValue >= MinValue && QuantityValue <= MaxValue))
                bindingContext.ModelState.AddModelError("Quantity", "Quantity not between values");
    
            return bindingContext.Model;
        }
    }
    

    Register Custom Model Binder:

    ModelBinders.Binders.Add(typeof(QuantityViewModel), new VarQuantity());
    

    Test Controller Action Methods:

        public ActionResult Quantity()
        {
            return View();
        }
    
        [HttpPost]
        public string Quantity(QuantityViewModel qvm)
        {
            if (ModelState.IsValid)
                return "Valid!";
            else
                return "Invalid!";
        }
    

    Test View Code:

    @model MvcTest.Models.QuantityViewModel
    
    

    Quantity

    @using (Html.BeginForm()) { @Html.Label("Enter Your Quantity: ") @Html.TextBoxFor(m => m.quantityModel.Quantity)
    @Html.Label("Quantity Minimum: ") @Html.TextBoxFor(m => m.QuantityMin)
    @Html.Label("Quantity Maximum: ") @Html.TextBoxFor(m => m.QuantityMax)

    }

提交回复
热议问题