r1993 r1993 - 3 months ago 48
ASP.NET (C#) Question

System.FormatException: String was not recognized as a valid Boolean

I am working on an ASP.NET MVC webform and attempting to get the value of the checkbox checked by the user. When running the application an exception is thrown and server error is diplayed on following line of code from the controller:

supp = Convert.ToBoolean(checksupp);


I have run visual studio on debug mode and the checkbox value is getting passed but is showing the following exception :


String was not recognized as a valid Boolean.


The models, views and controllers are shown below and not sure how to resolve this issue.

Model

public class WebFormXML{

private List<string> suppressions;

public WebFormXML()
{
suppressions = new List<string>();
}

public List<string> Suppressions
{
get { return suppressions; }
set { suppressions = value; }
}

{


View

<input type="checkbox" groupname="suppressions" name="suppressions" id="supp1" value="Prepayments" runat="server" />


Controller

[HttpPost]
public ActionResult createXML(FormCollection collection)
WebFormXML wfx = new WebFormXML();
string checksupp = collection["suppressions"];
bool supp = true;
supp = Convert.ToBoolean(checksupp);
wfx.Suppressions.Add(checksupp);

Answer

This is occurring because the value you are expecting to read is actually "Prepayments" as opposed to a value that can be converted to a boolean (e.g. "true" or "false").

Checkbox Submission

Checkboxes by default will only submit checked values, so you shouldn't need to perform any other checks to see if other options were checked. If you need to handle multiple possible selections, simply iterate through your checked options and add each of them :

[HttpPost]
public ActionResult createXML(FormCollection collection)
{
     // Build your WebForm object
     WebFormXML wfx = new WebFormXML();
     // Get your suppressed items
     var suppressions = collection["suppressions"].Split(',');
     // Add each of them to your object
     wfx.Suppressions.AddRange(suppressions);

     // Other code here
}

Example

enter image description here

You can see a very basic working example of this demonstrated here and seen below :

Controller

[HttpPost]
public ActionResult Index(FormCollection collection)
{
    // Get your suppressed elements (they will come in as a comma-delimited string)
    var suppressions = collection["suppressions"];
    return Content("Properties: [" + suppressions + "] were suppressed.");
}

View

@using (Html.BeginForm())
{
    <b>A</b>
    <input type="checkbox" groupname="suppressions" name="suppressions" value="A" /> 
    <b>B</b>
    <input type="checkbox" groupname="suppressions" name="suppressions" value="B" /> 
    <b>C</b>
    <input type="checkbox" groupname="suppressions" name="suppressions" value="C" /> 
    <br />
    <button type="submit">Check Suppressions</button>
}