0

I need to display 6 types of tests on my view and allow the user to check as many tests as they'd like to complete. I will then need to send their response to my controller so I can add that information to a database using the entity framework.

my View:

@using (Html.BeginForm("Quote", "Customers", FormMethod.Post))
{
    <label for="test1"> BP</label>
    @Html.CheckBox("test1", true)<br />

    <label for="test2"> DS</label>
    @Html.CheckBox("test2")<br />

    <label for="test3"> IS</label>
    @Html.CheckBox("test3")<br />

    <label for="test4" class="iput">PS</label>
    @Html.CheckBox("test4")<br />

    <label for="test5">PF</label>
    @Html.CheckBox("test5")<br />

    <label for="test6">CS</label>
    @Html.CheckBox("test6")<br />

    <input type="submit" value="Begin Quote" class="btn btn-default" style="padding-left: 20px" />
} 

and my controller method:

[HttpPost]
        public ActionResult Quote(FormCollection collection )
        {

            if (!string.IsNullOrEmpty(collection["test1"]))
               {
                   string checkResp = collection["test1"];
                   bool checkRespB = Convert.ToBoolean(checkResp);
               }


            return View("Index");
        }

I am running into an issue when debugging...The collection["test1"] is returning a "true, false" value instead of the actual checked value of the checkbox. I cannot seem to get the form to collect the actual statuses of the check boxes.

I have tried other options but none have seemed to work. Any help is greatly appreciated!

Adam M
  • 1
  • 1
    Have you tried creating a view model and creating `@Html.CheckBoxFor`, then have your post action receive that view model instead of `FormCollection`? I think the `@Html` helper creates a hidden input along with every checkbox for the model binder ... see this [SO Post](https://stackoverflow.com/questions/2697299/asp-net-mvc-why-is-html-checkbox-generating-an-additional-hidden-input) – zgood Dec 04 '19 at 18:53
  • I will try that now, thanks! Do I need to change the syntax I used to start the form then? This--> @using (Html.BeginForm("Quote", "Customers", FormMethod.Post)) – Adam M Dec 04 '19 at 19:30
  • No you won't have to change any of that. Make a view model like `QuoteVM` with properties like `public bool test1 {get; set;}`, then declare the model at the top of your view - `@model QuoteVM` then you can use `@Html.CheckBoxFor` and then finally update your post action to `public ActionResult Quote(QuoteVM model)` and the model properties should be bound properly - i.e. true if checked and false if not checked – zgood Dec 04 '19 at 19:43

0 Answers0