I have a view model:
public class RegisterModel
{
...
public bool Confirmation{ get; set; }
}
I am using checkbox helper in my view:
@model RegisterModel
......
@Html.CheckBoxFor(m => m.Confirmation)
This html helper flag creates:
<input id="Confirmation" name="Confirmation" value="true" type="checkbox">
<input name="Confirmation" value="false" type="hidden">
On the controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (!ModelState.IsValid)
return View(model);
.....
}
Let's say some users change the input values ββto "xxx" and publish it. Therefore, the model is invalid and we return the view. After that it Html.CheckBoxForwill give this error:
Converting parameters from type 'System.String' to type Error 'System.Boolean'.
Internal exception:
System.FormatException: xxx is not a valid value for Boolean
When we return the display: Model.Confirmationthe value to false , but the Request["Confirmation"]value of the 'xxx' .
ValueProviderResult ConvertSimpleType. , Request["Confirmation"] boolean .
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Conversion failure is not fatal")]
private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType)
{
.....
TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
bool canConvertFrom = converter.CanConvertFrom(value.GetType());
if (!canConvertFrom)
{
converter = TypeDescriptor.GetConverter(value.GetType());
}
if (!(canConvertFrom || converter.CanConvertTo(destinationType)))
{
if (destinationType.IsEnum && value is int)
{
return Enum.ToObject(destinationType, (int)value);
}
string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists,
value.GetType().FullName, destinationType.FullName);
throw new InvalidOperationException(message);
}
.....
}
?