How to fix a System.FormatException when dropdownlist is set to default?

后端 未结 1 1607
青春惊慌失措
青春惊慌失措 2021-01-26 11:36

I am having \"An exception of type \'System.FormatException\' occurred in mscorlib.dll but was not handled in user code.\" Additional information: Input string was not in a corr

相关标签:
1条回答
  • 2021-01-26 11:50

    Before calling the Convert.ToInt32 method, you need to check the value of the string parameter and make sure it is some value which can be safely converted to an int value.

    Int32.TryParse method will he handy

    public JsonResult LoadAccsByCarrierId(string carrierid)
    {
         int id;
         var accsData =new List<SelectListItem>();
         if (Int32.TryParse(carrierid, out id))
         {
            var accsList = this.GetAccs(id);
            accsData = accsList.Select(m => new SelectListItem()
            {
                Text = m.AccessoryName,
                Value = m.AccessoryID.ToString(),
            }).ToList();
         }
         return Json(accsData, JsonRequestBehavior.AllowGet);
    }
    

    The above code currently returns an empty list of SelectListItem when the carrierId parameter value is not a valid numerical string value. Update the code to return everything (no filtering) as needed.

    I also suggest to use the appropriate types. If carrierId is going to be always an int value or no value, you might consider using a nullable int and avoid the TryParse method call on string.

    public ActionResult LoadAccByCarrierId(int? carrierId)
    {
      if(carrierId!=null)
      {
           // to do : use carriedId.Value to do the Filtering
      }
      else
      {
        return something else 
      }
      // to do  : Return something
    }
    
    0 讨论(0)
提交回复
热议问题