mvc edit product in csharp

To edit a product in an MVC architecture using C#, you can follow the below steps:

  1. Add an Edit action method in the controller:
main.cs
public ActionResult Edit(int id)
{
    // Get product by id from the database
    var product = db.Products.Find(id);

    // If the product does not exist, return a not found error
    if (product == null)
    {
        return HttpNotFound();
    }

    // Return the edit view with the product as the model
    return View(product);
}
337 chars
15 lines
  1. Create an Edit view with a form to edit the product:
main.cs
@model YourApp.Models.Product

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}
1261 chars
34 lines
  1. Add the HttpPost Edit action method to handle the form submission:
main.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product)
{
    if (ModelState.IsValid)
    {
        // Update the product in the database
        db.Entry(product).State = EntityState.Modified;
        db.SaveChanges();

        // Redirect to the product details page
        return RedirectToAction("Details", new { id = product.Id });
    }

    // If the model state is not valid, return the edit view with the same product model
    return View(product);
}
486 chars
18 lines
  1. Use the Html.ActionLink to generate a link to the Edit action method:
main.cs
@Html.ActionLink("Edit", "Edit", new { id = Model.Id })
56 chars
2 lines

This will generate a link that will take you to the Edit action method with the product id as a parameter.

That's it! You can now edit your products using an MVC architecture in C#.

gistlibby LogSnag