So I'm creating a website with MVC4. Essentially what I have is a table of licenses, with a bunch of properties. I want to be able to add checkboxes to this table so that when you select a group of licenses and click the submit button it will allow you to bulk edit a select few properties of the selected licenses (for example, the issued dates on them). I can't seem to find an easy way to implement this.
-
As you are using checkbox, associate it to a bool property in your model. Then, when you'll post the form, just iterate in your posted model looking for the bool properties where value equals true.Thiago Custodio– Thiago Custodio2013-08-14 19:22:31 +00:00Commented Aug 14, 2013 at 19:22
Add a comment
|
1 Answer
I'm not sure if there is an easy way to do this. However, I'll propose one solution. The steps are:
- There's one action sending a list of licenses to a view
- The view presents them in a table and lets the use edit
- The view posts this list to another action
- This action receives all the licenses, editted or not
So, let's dig into it.
Model
public class License
{
public int Id { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
}
1st action
public ActionResult Index()
{
List<License> viewModel = new List<License>();
viewModel.Add(new License() { Id = 1, Name = "Whatever" });
viewModel.Add(new License() { Id = 2, Name = "Whatever else" });
viewModel.Add(new License() { Id = 3, Name = "Nevermind this one" });
return View(viewModel);
}
View
@using (Html.BeginForm("Save", "Home"))
{
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Notes</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
@{
int i = 0;
foreach (MVC4.Test.Models.License l in Model)
{
<tr>
<td><input type="text" name="licenses[@i].Id" readonly value="@l.Id"/></td>
<td><input type="text" name="licenses[@i].Name" readonly value="@l.Name" class="_mayEdit" /></td>
<td><input type="text" name="licenses[@i].Notes" readonly value="@l.Notes" class="_mayEdit"/></td>
<td><input type="checkbox" class="_edit" /></td>
</tr>
i++;
}
}
</tbody>
</table>
<input type="submit" value="Save" />
}
<script type="text/javascript">
$(function () {
$('._edit').click(function () {
if ($(this).is(':checked'))
$(this).parent().parents('tr').find('._mayEdit').removeAttr('readonly');
else
$(this).parent().parents('tr').find('._mayEdit').attr('readonly', 'readonly');
});
});
</script>
2nd action
[HttpPost]
public ActionResult Save(License[] licenses)
{
return View();
}
A few things to note:
- I'm using jQuery
- Pay attention to that index when creating the inputs. It must start at 0 and increment by 1. This is the only way for the model binding understands that this is a collection of items
- At the 2nd action, you may manipulate that list. Save it to a database or whatever.