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
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
}