I am presenting the question with the wording shown so that it indicates what I am really trying to do. While I could present the question as, "How can I use jQuery to read a table's contents an convert to type IEnumerable<ModelName>
?" I would be hiding important context that could suggest a far better way of achieving this outcome, which is what I'm really hoping for.
When auto-scaffolding a controller and views from a model (using Entity Framework), the resulting view allows one to edit one record at a time by clicking the row, editing the record, and returning to the Index. For many cases that is the desired functionality.
But what about when one wants to mass-update values in a table, as if one were working on a spreadsheet. For example, toggle some checkboxes and click "Update", like in this scenario.
One working idea I have is to use jQuery to:
- Read the table data and convert into a variable of type
IEnumerable<SampleModel>
. - Pass the table contents to a public void method in the controller.
- Notify the user that the action was successful and refresh the page.
It's really #1 where I am stuck because I need to be able to pass an object of type IEnumerable<SampleModel>
to the controller's method, and I do not know how to do this.
Controller:
public void UpdateTable(IEnumerable<SampleModel> query)
{
// I'm verifying existence before writing code here.
// This is where I'll be updating the database.
Debug.WriteLine("Test for query existence " + query.Count());
}
View:
@model SampleSystem.Areas.FakeName
<button id="UpdateTableTop">Update</button>
<table class="table">
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.Reconciled)
</th>
<th>
@Html.DisplayNameFor(model => model.StudentID)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.HiddenFor(modelItem=>item.ID)
</td>
<td>
@Html.CheckBoxFor(modelItem => item.Reconciled)
</td>
<td>
@Html.DisplayFor(modelItem => item.StudentID)
</td>
</tr>
}
</table>
@section scripts {
<script>
$(function () {
$("UpdateTableTop").click(function (e) {
$.ajax({
url: '@Url.Action("UpdateTable")',
data:
/* ... Need to convert table
* to IEnumerable<SampleModel> ...
*/,
success: function (){
console.log("Success!");
}
});
});
});
</script>
}