How can I dynamically create checkboxes based on query results in an MVC application for the web API?

I need to create a "virtual" CheckedListbox (a bunch of flags in a container), that is, N flags based on the results of a SQL Server query. I have a placeholder html where the checkboxes are currently 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 checkboxes in response to a result set. The html above is on the page \ Views \ Home \ Index.cshtml, so I assume that the "code-behind" belongs to the file \ Controllers \ HomeController.cs, but I don’t know what to do there. I currently have standard / boilerplate code:

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

Hope I can do something like this:

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

... or more realistic more:

 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 by implementing Prasad Raji'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

Moving the code from the div and into the code block (a reasonable 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 do not see the checkboxes on the page:

enter image description here

UPDATE 3

It turns out that it was a stupid add-in on my part (I would say, “rookie mistake,” but I'm not a rookie). After changing this line in the controller:

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

... to that:

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

... it works fine (there was nothing to migrate, so it is not surprising that no flags were created).

+6
source share
4 answers

Try this simple example for you.

REGULATOR

 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> 

Exit

enter image description here

+2
source

You can use the model and db request from the controller. In ASP.NET MVC, he considered it very bad practice to query the database directly from the view (as opposed to how this is done for ASP.NET web forms).

Controller:

  public DataTable MockDataTable { get { DataTable dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("CheckBoxes"); dt.Rows.Add(new object[] { "Alex", "Hello" }); dt.Rows.Add(new object[] { "Alex", "World" }); dt.Rows.Add(new object[] { "Alex", "Etc" }); return dt; } } public ActionResult Index() { // here you do your db query DataTable dt= MockDataTable; // convert it to List<string> List<string> result = dt.Rows.OfType<DataRow>() .Select(dr => dr.Field<string>("CheckBoxes")).ToList(); return View(result); } 

View:

 @model IEnumerable<string> <div class="container" name="unitsCheckboxDiv"> @foreach (var item in Model) { <input type="checkbox" />@item<br /> } </div> 
+1
source
 This classes/ structs need to be in /Models folder. Use struct opposed to class as it is lightweight and suitable in your case. Also except we have MVVM situation of two way data binding, we might just want to read so public {set; } is unnecessary. public struct CheckBoxViewModel { public CheckBoxViewModel(string name) { this.Name = name; } internal CheckBoxViewModel(DataRow row)// because I assume you know and will pass the correct Data from DataTable, this constructor might reduce some extra code. { this.Name = row["Name"] + ""; } public string Name { get; private set; } } public static class common { public static IEnumerable<CheckBoxViewModel> GetList() { var list = new List<CheckBoxViewModel>(); IDbCommand dbc = db.CreateCommand(); //db is your connection a static one. using (var r = dbc.ExecuteReader(CommandBehavior.SequentialAccess)) { while (reader.Read()) { var cbvm = new CheckBoxViewModel(reader.GetString(0));// assuming 0 is the index of your column list.Add(cbvm); } } return list; } } public ActionResult Index() { return View(common.GetList()); } Now in your view, @model IEnumerable<CheckBoxViewModel> <div class="container" name="checkboxList"> @foreach (var item in Model) { <input type="checkbox" />@item.Name<br /> } </div> 
+1
source

Update:

@B. Clay Shannon, it seems you didn’t have a clear MVC concept, I would suggest you read ASP.NET MVC Getting Started from Part 1 first in Part 6, then change your codes as follows

First of all, you need a ViewModel that will be created in the ViewModels folder for your View Page

 public class CheckBoxViewModel { public string Name {get;set;} public string Description{get;set;} } 

Go to Index () of the HomeController, all you have to do is just put the result of the query in CheckBoxViewModel, I don’t know your query, so I assume this is just a list of strings, for example yours:

  public ActionResult Index() { var checkBoxViewModel = new IList<CheckBoxViewModel>(); foreach(var item in myDbEntities.Table.ToList()) { checkBoxViewModel.add(new CheckBoxViewModel{ Name = item.Name Description = item.Description }); } return View(checkBoxViewModel); } 

Secondly, go to the watch page. I assume this is a Home / Index based on your question.

Add this line at the top of the watch page.

 @model IEnumerable<MyProjectNamespace.ViewModels.CheckBoxViewModel> 

After that, you just loop your result and create checkboxes

 @foreach(var cb in model) { <input type="checkbox" id="@cb.Name" name="@cb.Name" >@item.Description<br/> } 
-one
source

All Articles