I am using a Entity Framework and JQuery to update values in an SQL table column with a bit data type. This is being done by reading the values into an html table and then having a button that will change the bit value for each row.
Here you can see the html table:
<table id="categoryList" class="table">
<thead>
<tr>
<th>Category ID</th>
<th>Category Name</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Categories)
{
<tr>
<td>@item.id</td>
<td>@item.name</td>
<td>
<button class="btn btn-success categoryEnabled" data-id="@item.id">Enabled</button>
</td>
</tr>
}
</tbody>
</table>
Then here is the script I am using to start the action on click:
$(".categoryEnabled").on("click", function() {
$(this).hide();
$(this).next().show();
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
DisableRow($(this).data('id'));
});
function DisableRow(id) {
$.post('@Url.Action("DisableRow", "Category")', { "Id": id }, function () {
alert('Row Disabled!');
}).fail(function () {
alert('Error disabling row!');
});
}
This is then linked to a controller action that should change the state bit value for the selected row and update:
public void DisableRow(int id)
{
var connection = new CategoryDBEntities();
var record = connection.Categories.Find(id);
if (record == null) return;
record.state = StatesTypes.Disabled;
connection.SaveChanges();
}
Here's Category object for reference:
namespace Project.Models
{
using System;
using System.Collections.Generic;
public enum StatesTypes
{
Disabled = 0,
Enabled = 1
}
public partial class Category
{
public int id { get; set; }
public string name { get; set; }
public StatesTypes state { get; set; }
}
}
DbContext:
namespace Project.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class CategoryDBEntities : DbContext
{
public QualityDBEntities()
: base("name=CategoryDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Category> Categories { get; set; }
}
}
Output from Diagnostics Debug:
SELECT TOP (2)
[Extent1].[id] AS [id],
[Extent1].[name] AS [name]
FROM [dbo].[Category] AS [Extent1]
WHERE [Extent1].[id] = @p0
-- p0: '5' (Type = Int32)
The issue is that the record.state is changed to disabled (0), but the bit value in the database does not change. I must be missing something here. Thanks for your help!
CategoryDBEntities:connection.Database.Log = s => Debug.WriteLine(s);. This will output the SQL that EF generates when you callSaveChanges(). What do you see?