lundi 18 avril 2016

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.




Aucun commentaire:

Enregistrer un commentaire