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);
}
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
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();" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With