Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'll try make this as simple as possible. So your <code>Course</code> model is something like this...</p> <pre><code>public class Course { public int Id { get; set; } public string Name { get; set; } public bool Assigned { get; set; } } </code></pre> <p>...and you want to display some saved values on screen to edit. So starting at the controller, I've dummied some data and set one of the <code>Assigned</code> booleans to <code>true</code> so it is checked when the page loads.</p> <pre><code>public Controller Courses { public ActionResult Edit(int id) { var courses = new Course[] { new Course() { Id = 1, Name = "maths", Assigned = true }, new Course() { Id = 2, Name = "english", Assigned = false }, new Course() { Id = 3, Name = "science", Assigned = false } }; return View(courses); } </code></pre> <p>Now, your page should expect a collection of these courses, so at the top of your page define the type that the <code>View</code> is expecting...</p> <p><strong>cshtml</strong></p> <pre><code>@model IEnumerable&lt;ExampleProject.Domain.Course&gt; </code></pre> <p>...which you can then enumerate through in your <code>View</code> and create your checkboxes.</p> <pre><code>@using (Html.BeginForm("Edit", "Courses", FormMethod.Post)) { @foreach(var item in Model) { &lt;label for="@item.Id"&gt;@item.Name&lt;/label&gt; &lt;input type="checkbox" name="courses" id="@item.Id" value="@item.Id" checked="@item.Assigned" /&gt; } &lt;button type="submit"&gt;Save changes&lt;/button&gt; } </code></pre> <p>This will render the following html:</p> <pre><code>&lt;label for="1"&gt;maths&lt;/label&gt; &lt;input type="checkbox" name="courses" id="1" value="1" checked="checked"&gt; &lt;label for="2"&gt;english&lt;/label&gt; &lt;input type="checkbox" name="courses" id="2" value="2"&gt; &lt;label for="3"&gt;science&lt;/label&gt; &lt;input type="checkbox" name="courses" id="3" value="3"&gt; </code></pre> <p>Now you can check what you like and submit your form. In true http fashion your controller action will receive the values were checked on the <code>View</code>:</p> <pre><code>[HttpPost] public ActionResult Courses(int id, int[] courses) { // courses will contain the values of the checkboxes that were checked return RedirectToAction("Index"); // etc } </code></pre> <p>Hopefully this helps. You can be a bit smarter and use the Html helpers for some more complicated binding (eg. <code>Html.CheckBox</code>, <code>Html.CheckBoxFor</code>) but this should get you going and it's clear to see what's going on.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload