0

I have to get checked checkboxes from table column. I have done this to achieve the require result but couldn't find the exact solution and return null value in http post.

    public ActionResult Index()
    {
        return View(db.Users.ToList());
    }
    [HttpPost]
    public ActionResult Index( List<User> user) 
    {
        return View(db.Users.ToList());
    }

View

@model IEnumerable<EntityframeworkDemo.User>

@using (Html.BeginForm())
{
<table class="table">
@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Phone)</td>
        <td>@Html.DisplayFor(modelItem => item.Email)</td>
        <td>@Html.DisplayFor(modelItem => item.C_Password)</td>
        <td>@Html.CheckBoxFor(modelItem => item.Validations.Value)</td>
    </tr> }
</table>
<input type="submit" value="Post" />
}

Model Class:

Class User
{
        public int U_id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string C_Password { get; set; }
        public bool? Validations { get; set; }
}
  • Please Provide Any Sample – Osama Danish Sep 08 '17 at 13:43
  • Do you have a reason for making the Validations bool nullable? – allen.mn Sep 08 '17 at 13:52
  • I m Using Validations Admin Active and Inactive Users – Osama Danish Sep 08 '17 at 14:18
  • If you want to use it for three states for a nullable bool, then check out the link @OrelEraki posted. I'd suggest an enum with Admin, Active, and Inactive to more clearly model your values. – allen.mn Sep 08 '17 at 14:24
  • I cannot Understand This Link Please You Apply My Code – Osama Danish Sep 08 '17 at 14:30
  • Not only can you not use a `foreach` loop (refer the dupe), You cannot bind a `bool?` to a checkbox - a nullable `bool` has 3 states, but a checkbox has only 2 states. You need `EditorFor()` which will generate a ` –  Sep 08 '17 at 23:23
  • I've tried all these but HttpPost method still getting null value – Osama Danish Sep 09 '17 at 06:46
  • Then you did not try correctly :) –  Sep 09 '17 at 13:02

1 Answers1

0

I suggest you handle Nullable boolean on Data Tier and when it comes to ViewModel make it regular boolean then your code should work

public bool Validations { get; set; } instead of

public bool? Validations { get; set; }

and

@Html.CheckBoxFor(modelItem => item.Validations)

instead of

@Html.CheckBoxFor(modelItem => item.Validations.Value)

On data tier check if your row is returning null and make it false when it does

CuriousRK
  • 69
  • 7