Kyle Preiksa
Kyle Preiksa

Reputation: 514

Getting Checkbox Values on postback ASP.NET MVC

I am writing an ASP.NET MVC application. I am a beginner so I'm sure this is really easy. I referenced ASP.NET MVC - How to get checkbox values on post but the code isn't available anymore, making it next to useless.

Here is my View:

@using (@Html.BeginForm("Promote", "FPL", FormMethod.Post))
{
<div data-role="fieldcontain">
<fieldset id="PromotionInfo" name="PromotionInfo">
<legend><b>@Model.itemType Promotion Details</b></legend>
    <label for="TargetDate">Target Date: </label>
    <input type="date" id="TargetDate" data-role="datebox" data-options='{"mode": "flipbox"}' />

    <label for="EmailCC">Email cc List: </label>
    <input type="email" id="EmailCC" />

    <div  data-role="fieldcontain">
    <fieldset data-role="controlgroup">
    <legend>Choose Destination Server(s): </legend>

    @foreach (DataRow server in Model.destinationServerList.Rows)
    {
    <label for="@server.ItemArray[0]">@server.ItemArray[1]</label>  
    <input type="checkbox" name="destinationServerSID" id="@server.ItemArray[0].ToString()"  />
    }

    </fieldset>
    </div>
</fieldset>

</div>

<input type="submit" value="Submit" />
} 

And here is my Controller:

    public ActionResult Promote(string id)
    {
        //Model(item) construction occurs here

        return View(item);
    }

    [HttpPost]
    public ActionResult Promote(FormCollection collection)
    {
        try
        {
            string[] test = collection.GetValues("destinationServerSID");
        }
        catch (Exception ex)
        {
            return null;
        }
    }

The test[] variable contains a 2 item array, both of which have the value "on" however, my list of items is longer than 2 items. It simply contains an "on" for every value you select, but no "off" values. I need the actual value of the checkbox(the id field).

Upvotes: 5

Views: 11243

Answers (2)

just.another.programmer
just.another.programmer

Reputation: 8785

Default HTML post behavior does not send values for unchecked boxes. You could use the Html.CheckboxFor method instead, it will generate all the necessary inputs to always post a value.

Upvotes: 3

Chuck Conway
Chuck Conway

Reputation: 16435

Ids are not posted to the server. Only name and value are posted to the server and only when the checkbox is checked.

Try setting the value attribute with @server.ItemArray[0].ToString().

<input type="checkbox" name="destinationServerSID" value="@server.ItemArray[0].ToString()"  />

Upvotes: 3

Related Questions