I'm having issues updating a Boolean from 'false' to 'true' in my database.
I am using Asp.Net MVC5 in Visual Studio 2017, and have created a database (using entity framework code-first) to contain two tables - task and steps (one-to-many relationship).
The index.cshtml page is laid out to list all of the tasks along with their relevant steps, and then each step has a 'mark as completed' button beside it to change the 'completed' field in the steps entity from false to true.
Here is my code:
Steps.cs:
public class Steps
{
[Key]
public int Id { get; set; }
public int StepNumber { get; set; }
public string Description { get; set; }
public ToDoTask Task { get; set; }
public bool Completed { get; set; }
public DateTime? CompletedDate { get; set; }
public Client Client { get; set; }
}
Index.cshtml:
@foreach (var step in ViewData["steps"] as Dictionary<Steps, int>)
{
if (step.Value == task.Id)
{
<p>Step Number: @step.Key.StepNumber</p>
<p>Step Description: @step.Key.Description</p>
using (@Html.BeginForm("MarkStepAsCompleted", "Tasks"))
{
<div class="col-md-2" style="display:none">
@Html.TextBox("Id", @step.Key.Id)
</div>
<button type="submit" >Mark As Completed</button>
}
}
}
TasksController.cs:
[HttpPost]
[AllowAnonymous]
public ActionResult MarkStepAsCompleted(FormCollection form)
{
var completedStepId = Convert.ToInt32(form["Id"]);
var completedStep = db.Steps.Where(s => s.Id == completedStepId).FirstOrDefault();
StepMethods.MarkAsCompleted(completedStep);
return Redirect("Index");
}
StepMethods.cs:
public static void MarkAsCompleted(Steps step)
{
var context = new ApplicationDbContext();
var stepid = step.Id;
context.Steps.Find(stepid);
step.Completed=true;
context.SaveChanges();
}
The application runs well with no errors and when I hit the 'Mark As Completed' button, it redirects to the index page as wanted. But when I check the table in Server Explorer, the value in the 'Completed' column still says false.
context.Steps.Attach(step); step.Completed=true; context.SaveChanges();