Click here to Skip to main content
14,872,753 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to create checkboxlist in ASP.NET MVC. I tried it from tutorial provided below
Creating Simple Checkboxlist in MVC 4 Using Razor[^]

I am facing an issue which I am not able to resolve.
Below is the code for the same.

C#
//Model
namespace MvcCheckBox.Models
{
   public class CheckModel
   {
      public int Id{get;set;}
      public string Name{get;set;}
      public bool Checked{get;set;}
   }
}
//Controller
namespace MvcCheckBox.Controllers
{
   public class HomeController:Controller
   {
      [HTTPGet]
      public ActionResult Index()
      {
         var list=new List<CheckModel>{new CheckModel{Id=1,Name="A",Checked=false},
                                     new CheckModel{Id=2,Name="B",Checked=false},};
         return View(list);
      }
      [HTTPPost]
      public ActionResult Index(List<CheckModel> list)
      {
         return View(list);
      }
   }
}

HTML
//View
@model List<MvcCheckBox.Models.CheckModel>
@{
   viewBag.Title="Index";
}
<h2>Index</h2>
@using(Html.BeginForm())
{
   for(var i= 0;i<Model.Count;i++)
   {
      <table><tr>
         <td>
            @Html.HiddenFor(it=>it[i].Id)
            @Html.HiddenFor(it=>it[i].Name)
         </td>
         <td>
            @Html.CheckBoxFor(it=>it[i].Checked,new{Style="vertical-align:3px"})
         </td>
      </tr></table>
   }
   <input id="Submit1" type="submit" value="Submit"/>
}


Issue:
When I run the code output is exactly how it should be i.e. name and checkbox is rendered.
After checking checkbox and clicking on submit, it doesn't displays name, i.e. during postback checkbox is rendered without name. After applying breakpoint, list shows "Name" property as empty.
I am not able to understand the problem.
I'm new to ASP.NET MVC, so still experimenting with MVC.

Thanks & Regards
Hari

What I have tried:

I don't know what to try or search. Any help/suggestion are welcome and will try to implement it.
Posted
Updated 3-Dec-20 3:57am
v3

Hi,

You are trying to give same id for the check boxes

that is not possible

try with diffrent id
   
Comments
hari19113 23-Dec-16 5:14am
   
Sorry sir, that's a typo mistake. In actual code I have provided distinct values. Sorry for the trouble. I'll edit the code.
hari19113 23-Dec-16 5:16am
   
Sorry sir, that's a typo mistake. In code I've provided "Id" with distinct value.
Sorry for the trouble, I've improved the question.
use CheckBox($"it[{@i}].Checked",Model[i].checked [,options)
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900