Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation Error: The value 'on' is not valid for <<property name>>

In my project, I have a model that you can see part of my model here:

public class CheckoutModel
{
    public bool OtherPlace { get; set; }

    [RequiredIf("OtherPlace", true, ErrorMessage = " ")]
    public string OtherPlaceFullName { get; set; }

    [RequiredIf("OtherPlace", true, ErrorMessage = " ")]
    public int OtherPlaceProvinceId { get; set; }

    [RequiredIf("OtherPlace", true, ErrorMessage = " ")]
    public string OtherPlaceCity { get; set; }
}

I used RequiredIf attribute to validate my model in view,

 if (!ViewData.ModelState.IsValid)
    {
        @Html.ValidationSummary(false)
    }

I fill all property of my form but I get below validation error when OtherPlaceProvinceId is not filled.

The value 'on' is not valid for OtherPlace.

UPDATE: The controller is here:

    [HttpGet]
    public ActionResult CheckoutAccount()
    {
        var model = OrderManager.Instance.GetCheckoutAccount();
        return View("_CheckoutAccount", model);
    }

    [HttpPost]
    public ActionResult CheckoutAccount(CheckoutAccountModel model)
    {
        return View("_CheckoutAccount", model);
    }
like image 860
user3206982 Avatar asked Jan 19 '14 18:01

user3206982


2 Answers

Is OtherPlace a checkbox? The default value for a checkbox is on if it's ticked & blank if it's not. The ModelBinder doesn't understand this.

ASP.Net deals with this, if you use the helpers, by doing this:

<input type="checkbox" name="OtherPlace" value="true"/>
<input type="hidden" name="OtherPlace" value="false"/>

The modelbinder will now figure out of the checkbox was ticked or not, convert it to a boolean & bind it to your model.

You could also use radio buttons with true/false values

like image 117
Simon Halsey Avatar answered Oct 01 '22 12:10

Simon Halsey


I'll do some workaround when you don't have too many inputs with this behavior.
It's simple, before you submit the form, catch the inputs with the 'on' string and change it for the true/false value.

function toggle_validator(e) {
    if ($('#OtherPlace').val() == 'on') {
        $('#OtherPlace').val(true);
    }
    else {
        $('#OtherPlace').val(false);
    }
}

And we need to bind this event to the button that submit the form.

<input type="submit" value="Save" class="btn btn-success" onclick="toggle_validator();" />
like image 39
Ivan-San Avatar answered Oct 01 '22 14:10

Ivan-San