-2

How can i get checkbox values in controller mvc 4 ? I want to send checkbox value to controller and save changes in database. I am using Entity Framework 4.5 and MVC4 databasefirst.

  • Show your model, your view and the controller. What have you tried. –  May 07 '15 at 08:11

1 Answers1

0

firstly create view model

 public class UnitVM 
    {
    public List<Unit> UnitObj { get; set; }
}

public class Unit
    {
    public int Id { get; set; } 
    public string RoomNo { get; set; }
    public bool CheckedStatus { get; set; }
}

Then in controller, create "HttpGet" action to bind checkboxlist.

Dont forget to add

using BootMvcApplication3.Models;

using System.Text;

[HttpGet]
    public ActionResult Med()
    {
        UnitVM obj = new UnitVM(); // Create object of viewmodel
        obj.UnitObj = BindUnits(); // function to bind checkboxlist values
        return View(obj);
    }

    public List<Unit> BindUnits()
    {
        List<Unit> obj = new List<Unit>();
        var trverse = dbContext.ALFUnits.Where(x => x.UNITSiteCode.Equals("AZA"));

        foreach (var i in trverse)
        {
            obj.Add(new Unit { Id = i.Id, RoomNo = i.RoomNo });
        }

        return obj;
    }

[HttpPost]
    public ActionResult Med(UnitVM obj)
    {

        StringBuilder sb = new StringBuilder();

        foreach (var item in obj.UnitObj)
        {
            if (item.CheckedStatus == true)
            {
                sb.Append(item.RoomNo + ", ").AppendLine();
            }
        }

        ALFMedcartMaster add = new ALFMedcartMaster();

        add.Room = sb.ToString(); //Store checked Room nos. in "101,102,103" this format

        dbContext.ALFMedcartMasters.Add(add);
        dbContext.SaveChanges();
        return View();
    }

In View

@model BootMvcApplication3.Models.UnitVM

for (int i = 0; i < Model.UnitObj.Count; i++)
        {
                    @Html.CheckBoxFor(m => Model.UnitObj[i].CheckedStatus)
                    @Model.UnitObj[i].RoomNo
                    @Html.HiddenFor(m => Model.UnitObj[i].Id)
                    @Html.HiddenFor(m => Model.UnitObj[i].RoomNo)

        }

<input type="submit" value="Update" />

Here in view "CheckedStatus" is required to save true & false value and "@Model.UnitObj[i].RoomNo" is for displaying actual room no.