5

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).

2 Answers 2

3

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()"  />
Sign up to request clarification or add additional context in comments.

1 Comment

wow, I can't believe I missed that... Thank you so much, that is all I needed.
3

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.

1 Comment

This would work too, however the answer about passing it as a value instead of an id was all i needed. Thank you for answering!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.