Home > DeveloperSection > Forums > How to get checked value of checkbox in MVC 4
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    February-02-2013 3:06 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 11143  View(s)
Rate this:

Hi Everyone!
I have created dynamicaly checkbox in partial view in MVC 4. How to get checked value of checkbox in action when form post. Dynamicaly generated checkbox code as below

@using (Html.BeginForm("AttachmentList", "Home", FormMethod.Post, new
{
    @id = "PDFListDownload"
}))
{
    <div id="PDFAttachmentList">
        <table>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@Html.CheckBox("fileItem")
                        @Html.Hidden("fileId", item.AtttachmentID)
                    </td>
                    <td>@Html.DisplayTextFor(m => item.Description)
                    </td>
                </tr>
            }
            <tr>
                <td>
                    <input id="btnDownload" type="submit" value="Download"  />
                </td>
                <td>
                    <input id="btnCancel" type="button" value="Cancel" onclick="CloseDialog();" />
                </td>
            </tr>
        </table>
    </div>
}

Thanks and regard!



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    February-02-2013 5:27 AM

Hi Royce Roy!

Post your View or Partial View to Action as below code and identify which checkbox are checked based on Hidden field ID(acording your code).

[HttpPost]
        public ActionResult AttachmentList(FormCollection formData)
        {
            var fileIds = formData["fileId"].Split(',');
            var selectedIndices = formData["fileItem"].Replace("true,false", "true").Split(',').Select((item, index) => new
            {
                item = item,
                index = index
            }).Where(row => row.item == "true").Select(row => row.index).ToArray();

            if (selectedIndices.Count() > 0)
            {
  foreach (var index in selectedIndices)
                {
   int checkedID = fileIds[index]; // Here "CheckedID" is checked checkbox id. You can populate condition according this value.
  }
     }
 }


Don't want to miss updates? Please click the below button!

Follow MindStick