Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically create checkboxes based on query results in my Web API MVC app?

I need to create a "virtual" CheckedListbox (a bunch of checkboxes in a container) - that is, N checkboxes based on the results of a SQL Server query. I have placeholder html where bogus checkboxes are currently being placed on the page:

<div class="container" name="unitsCheckboxDiv">
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
    <input type="checkbox" /> This is checkbox <br />
</div>

...but I need to create the checkboxes in response to the result set instead. The html above is in the \Views\Home\Index.cshtml page, so I assume the "code-behind" belongs in the \Controllers\HomeController.cs file, but I don't know what to do there. Currently I just have the default/boilerplate code there:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    . . .

I hope I can do something like this:

Page_Load()
{
    DataTable dt = GetUnits();
    unitsCheckBoxDiv.DataSource = dt;
}

...or more realistically more like so:

Page_Load()
{
    DataTable dt = GetUnits();
    foreach (string unit in dt)
    {
        CheckBox cb = new Checkbox();
        cb.Value = unit;
        unitsCheckBoxDiv.AddHTMLElement(cb);        
    }
}

...but I don't know how to make this vague idea more concrete.

UPDATE

I think I'm on the right track implementing Prasad Raja's answer, but with this code:

HomeController.cs:

using System.Data;
using System.Web.Mvc;

namespace WebAppRptScheduler.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DataTable dtable = new DataTable();
            SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);
            ViewBag.Units = dtable;
            return View();
        }

    . . .
    }
}

Index.cshtml:

@using System.Data
@{
    ViewBag.Title = "Report Scheduler";
}

<div class="jumbotron">
    <h1>Report Scheduler</h1>

    DataTable ds = ViewBag.Units as DataTable;
    var rows = from x in ds.AsEnumerable()
    select new
    {
        unit = x.Field<string>("unit")
    };
</div>

<div class="row">
    <div class="col-md-6">
        <h2>Configure One Unit/Report pair at a time</h2>
        <h4>Select a Unit</h4>
        @foreach (var item in rows)
        {
            <input id="ckbx_@(item.unit)" type="checkbox" value="@item.unit" />
            @item.unit <br />
        }
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-6">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
</div>

...I get this runtime error (it compiles, although it says "Compilation Error"):

enter image description here

UPDATE 2

By moving the code out of the div and into the code block (a sensible move):

@using System.Data
@{
    ViewBag.Title = "Report Scheduler";

    DataTable ds = ViewBag.Units as DataTable;
    var rows = from x in ds.AsEnumerable()
               select new
               {
                   unit = x.Field<string>("unit")
               };
}

...I can get further, but I still see no checkboxes on the page:

enter image description here

UPDATE 3

It turns out it was a dumb oversight on my part (I would say, "a rookie mistake" but I'm no rookie). After changing this line in the Controller:

SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);

...to this:

dtable = SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);

...it works fine (there was nothing to loop over, so no wonder no checkboxes were generated).

like image 518
B. Clay Shannon-B. Crow Raven Avatar asked Apr 18 '16 23:04

B. Clay Shannon-B. Crow Raven


1 Answers

Try this simple example to you

COntroller

public ActionResult Index()
        {
            DataTable dtable = new DataTable();
            dtable.Columns.Add("id", typeof(int));
            dtable.Columns.Add("name", typeof(string));

            // adding few data to table
            dtable.Rows.Add(1, "Prasad");
            dtable.Rows.Add(2, "Raja");
            dtable.Rows.Add(3, "Hemenath");
            dtable.Rows.Add(4, "Rajesh");
            dtable.Rows.Add(5, "Suresh");
            dtable.Rows.Add(6, "Daniel");
            ViewBag.Units = dtable;
            return View();
        }

View

@using System.Data
@{
    ViewBag.Title = "Index";


    DataTable ds = ViewBag.Units as DataTable;
    var rows = from x in ds.AsEnumerable()
               select new
               {
                   id = x.Field<int>("ID"),
                   name = x.Field<string>("name")
               };
}
<div class="form-horizontal">
    <h4>
        Select your favourite Name</h4>
    @foreach (var item in rows)
    {  
        <input id="chk_@(item.name)"   type="checkbox"  value="@item.id"   />
        @item.name <br />  
    }
</div>

Output

enter image description here

like image 106
Prasad Raja Avatar answered Oct 21 '22 06:10

Prasad Raja