Problem with ASP.NET Checkbox "The Parameter Conversion from type 'System.String' to type 'System.Boolean' failed."

Asked

Viewed 283 times

0

I’m having the following problem with a checkbox

I have a checkbox list that is dynamically loaded (as the items that exist in the bank a checkbox is generated). I currently have only three items being ids 1, 2 and 3. Within the system when I have saved the object containing a list of these items is passed by some validations, and when it returns to the View the system validation message is displayed, if I select a checkbox for ID 2 or 3 the flow works normally, when I select the checkbox with id 1 all part of the backend works normally but when it returns to the view and when trying to render the checkbox again returns the following error:

 [FormatException: Cadeia de caracteres não foi reconhecida como Boolean válido.
   System.Boolean.Parse(String value) +12394192
   System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) +123

FormatException: 1 não é um valor válido para Boolean.
   System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) +281
   System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType) +393

InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information.]
   System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType) +541
   System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType) +258
   System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture) +51
   System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) +70
   System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, String format, IDictionary`2 htmlAttributes) +245
   System.Web.Mvc.Html.InputExtensions.CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String name, Nullable`1 isChecked, IDictionary`2 htmlAttributes) +153
   System.Web.Mvc.Html.InputExtensions.CheckBox(HtmlHelper htmlHelper, String name, Object htmlAttributes) +40
   ASP._Page_Views_SolicitacaoServico_Inserir_cshtml.Execute() in c:\Projetos\VALERENDA\ValeRenda\ValeRendaMVC\Views\SolicitacaoServico\Inserir.cshtml:65
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765045
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

CSHTML where Checkbox is generated

<label>Ocorrências</label>
<div class="checkbox-list">
    @if (TempData["SelecionarOcorrencia"] != null)
    {
        if (((List<TipoOcorrenciaViewModel>)TempData["SelecionarOcorrencia"]).Count() > 0)
        {
            foreach (TipoOcorrenciaViewModel item in (List<TipoOcorrenciaViewModel>)TempData["SelecionarOcorrencia"])
            {
                <label>
                    @Html.CheckBox("OcorrenciasSelecionadas",  new { @Value = item.TipoOcorrenciaID})
                    @item.Descricao                                                              
                </label>  

            }
        }
    }
</div>

View Model

public class TipoOcorrenciaViewModel
    {

        public int TipoOcorrenciaID { get; set; }

        public string Descricao { get; set; }

        public string Sigla { get; set; }

        public bool Ativo { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Ocorrencia> Ocorrencia { get; set; }

        public bool ExigeAnexo { get; set; }

    }

I saw some responses related to similar errors but in different situations, I can’t identify what can be, since it only happens with ID 1 in others works perfectly

EDIT


I ran a test removing the item with id 1 from the list before rendering by selecting the first checkbox from the list of the same error when selecting the second works normal

  • 1

    If when you select Ids 2 and 3 everything works, but only for ID 1 it doesn’t work, try comparing the fields between these objects, as it seems that some field related to ID 1 needs to be converted/treated.

  • Opa Renan, I had already checked this, but I took another look for consciousness disengagement and there are no differences in the objects only the values of the same attributes

1 answer

0


I was able to solve it in a way I didn’t like very much, it was a palliative solution on the basis of in this post of Stackoverflow in English

I switched @Html.Checkbox with the html input tag

<label>
   @if (Model != null && @Model.OcorrenciasSelecionadas.Contains(item.TipoOcorrenciaID.ToString()))
   {
    <input type="checkbox" name="OcorrenciasSelecionadas" value="@item.TipoOcorrenciaID" checked>
   }
   else
   {
    <input type="checkbox" name="OcorrenciasSelecionadas" value="@item.TipoOcorrenciaID">
   }        
    @item.Descricao                                                              
</label>  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.