I have been working on an ASP.NET MVC 5 web application using Entity Framework 6 as an assignment for my Business Programming II class. Despite the fact that I know very little about programming, I have been making progress, but I have run into trouble. I am supposed to write CRUD operations for an online storefront based on the Northwind Traders database. I already have working code for reading from the database as well as adding and updating items in the database. Where I'm struggling is deleting items. The following requirement is listed in the assignment description:
Delete a product by making it discontinued so that the information is displayed in the database. Do NOT actually delete a product from the database.
I've tried a couple things to try and make this work, but all have failed for various reasons.
Here's the code to my current Delete
View (ignore any strange HTML formatting decisions, right now I'm focused on getting this functional):
@model NWTradersWeb.Models.Product
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Product: @Html.DisplayFor(model => model.ProductName)</h4>
<hr />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div >
<input type="submit" value="Yes" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>
I have tried editing my ProductsController.cs
to manually set the Discontinued
attribute to true as follows:
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
product.Discontinued = true;
db.SaveChanges();
return RedirectToAction("Index");
}
This works, but if I run the Edit
operation on the same product I'm unable to undo the change. I can deselect the Discontinued checkbox but it does not save after I submit the changes and the Index page still shows the product as discontinued.
Here's my code for the Edit
View and corresponding ProductsController.cs
methods, I'm unsure if these have anything to do with my problem but I will include them anyway:
View:
@model NWTradersWeb.Models.Product
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div >
<h4>Product: @Html.DisplayFor(model => model.ProductName)</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ProductID)
<div >
@Html.LabelFor(model => model.SupplierID, "SupplierID", htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.DropDownList("SupplierID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.SupplierID, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.QuantityPerUnit, htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.EditorFor(model => model.QuantityPerUnit, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.QuantityPerUnit, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.UnitPrice, htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.EditorFor(model => model.UnitPrice, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UnitPrice, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.UnitsInStock, htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.EditorFor(model => model.UnitsInStock, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UnitsInStock, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.UnitsOnOrder, htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.EditorFor(model => model.UnitsOnOrder, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UnitsOnOrder, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.ReorderLevel, htmlAttributes: new { @class = "control-label col-md-2" })
<div >
@Html.EditorFor(model => model.ReorderLevel, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ReorderLevel, "", new { @class = "text-danger" })
</div>
</div>
<div >
@Html.LabelFor(model => model.Discontinued, htmlAttributes: new { @class = "control-label col-md-2" })
<div >
<div >
@Html.EditorFor(model => model.Discontinued)
@Html.ValidationMessageFor(model => model.Discontinued, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div >
<div >
<input type="submit" value="Save" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Controller Methods:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID);
return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID);
return View(product);
}
My professor also alluded to making the Delete
operation redirect to a simpler Edit
page where we could toggle the Discontinued attribute. I think he may be alluding to a partial view but we have not covered that to my knowledge.
Please note: I consider myself a novice when it comes to programming. I've taken other classes but the instructors focused more on syntax than concepts and as such my foundation is incredibly weak. I might be clueless about certain things that other people take for granted. I want to go back and study the fundamentals after I graduate and self-study, but this is a required class for a degree that is almost completely unrelated to programming. Any tips, hints, even a nudge in the right direction would be greatly appreciated.
CodePudding user response:
Your Delete logic seems fine. What I would look at in more detail is your Edit.
Overall I am not a fan of ever passing Entities between the server and the view, especially accepting an entity from the view. This is generally a bad practice because you are trusting the data coming from the view, which can easily be tampered with. The same when passing data from a view to server, this can lead to accidentally exposing more information about your domain (and performance issues) just by having some "sloppy" JavaScript or such converting the model into a JSON model to inspect client-side. The recent case of the journalist being accused of "hacking" because they found extra information via the browser debugger in a Missouri government website outlines the kind of nonsense that can come up when server-side code has the potential to send far too much detail to a browser.
In any case, in your Edit method when you accept the bound Product after deactivating the Discontinued flag, what values are in that Entity model? For instance if you use Delete to set Discontinued to "True", then go to the Edit view for that product and un-check that input control and submit the form, in your "product" coming in the Edit page, what is the state of the product.Discontinued?
If the value is still "True" then there is a potential problem with your page binding where the EditorFor is not linking to that flag properly or the value is not deserializing into the Product entity. (a private
or missing setter?)
If it is coming back with what should be the correct value, then I would look at changing how you update entities. Code like this:
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
... is inherently dangerous as "product" is not an entity, it is a deserialized set of values used to populate an entity class. Ideally when updating data you would provide a ViewModel that won't be confused with an Entity class and contain just the fields that are allowed to be updated. Using your current code though with the entity class serving as that view model I would suggest something more like:
var dataProduct = db.Products.Single(x => x.Id == product.Id);
dataProduct.ProductName = product.ProductName;
dataProduct.Discontinued = product.Discontinued;
// ...
db.SaveChanges();
When it comes to possibly allowing the user to change FKs for things like categories, then you should eager load those relationships, compared the FK IDs then load and re-associate those "new" relationships in the entity loaded from data state. (Don't just replace the FK values.)
The reason for doing this rather than attaching and setting the state to modified:
- We perform a validation when loading the entity. If we get back an Id that doesn't exist, we can handle that exception. We can also filter data to ensure that the current user actually has permission to see the requested ID and can end a session if it looks like someone is tampering with data.
- We only update values that we allow to change, not everything in the entity. We can also validate to ensure that the values provided are fit for purpose before making changes.
- When copying values across, EF will only generate
UPDATE
statements for values that actually change if any actually change. Attaching and setting the entity state toModified
or usingUpdate
will always generate anUPDATE
statement replacing all values whether anything changed or not. (can have negative impacts on triggers or hooks in the DbContext for things like Auditing)