C# ASP.NET MVC CRUD 数据更新问题

问题描述 投票:0回答:1

我有一个拥有授权用户的项目,管理员可以使用管理员菜单创建、更新、删除产品。创建和删除作品没有问题。编辑时,我收到一条通知“请填写所有必填字段”,即使所有字段都已填写。此外,每当我提交编辑时,产品 ID 都会因某种原因切换为 0。

代码 -

Edit.cshtml.cs
:

public class EditModel : PageModel
{
    private readonly IWebHostEnvironment environment;
    private readonly ApplicationDbContext context;

    [BindProperty]
    public ProductDTO ProductDTO { get; set; } = new ProductDTO();

    public Product Product { get; set; } = new Product();

    public string errorMessage = "";
    public string successMessage = "";

    [BindProperty]
    public string SelectedCategory { get; set; }

    public EditModel(IWebHostEnvironment environment, ApplicationDbContext context) 
    {
        this.environment = environment;
        this.context = context;
    }

    public void OnGet(int? id)
    {
        if (id == null)
        {
            Response.Redirect("/Admin/Products/Index");
            return;
        }

        var product = context.Products.Find(id);

        if (product == null)
        {
            Response.Redirect("/Admin/Products/Index");
            return;
        }

        ProductDTO.Name = product.Name;
        ProductDTO.Brand = product.Brand;
        ProductDTO.Description = product.Description;
        SelectedCategory = product.ProductCategory.ToString();
        ProductDTO.Price = product.Price;
        ProductDTO.Gender = product.Gender;

        Product = product;
    }

    public void OnPost(int? id) 
    {
        if (id == null)
        {
            Response.Redirect("/Admin/Products/Index");
            return;
        }

        if (!ModelState.IsValid)
        {
            errorMessage = "Please complete all required fields";
            return;
        }

        var product = context.Products.Find(id); 

        if (product == null) 
        {
            Response.Redirect("/Admin/Products/Index");
            return;
        }

        // upd img if new img
        string newFileName = product.ImageFileName;

        if (ProductDTO.ImageFile != null)
        {
            newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            newFileName += Path.GetExtension(ProductDTO.ImageFile.FileName);

            string imageFullPath = environment.WebRootPath + "/products/" + newFileName;

            using (var stream = System.IO.File.Create(imageFullPath))
            {
                ProductDTO.ImageFile.CopyTo(stream);
            }

            string oldimageFullPath = environment.WebRootPath + "/products/" + product.ImageFileName; // del img
            System.IO.File.Delete(oldimageFullPath);
        }

        product.Name = ProductDTO.Name; // upd in db
        product.Brand = ProductDTO.Brand;
        product.Description = ProductDTO.Description ?? "";
        product.ProductCategory = (Product.Category)Enum.Parse(typeof(Product.Category), SelectedCategory);
        product.Price = ProductDTO.Price;
        product.Gender = ProductDTO.Gender;
        product.ImageFileName = newFileName;

        context.SaveChanges();

        Product = product;
        successMessage = "Product updated successfully";

        Response.Redirect("/Admin/Products/Index");
    }
}

Edit.cshtml
查看:

@page
@model ShoeStore.Pages.Admin.Products.EditModel
@using ShoeStore.Models

@{
}

<div class="row">
    <div class="col-md-8 mx-auto rounded border p-3">
        <h2 class="text-center mb-5">Edit Product</h2>

        @if (Model.errorMessage.Length > 0)
        {
            <div class='alert alert-warning alert-dismissible fade show' role='alert'>
                <strong>@Model.errorMessage</strong>
                <button type='button' class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        }
        else if (Model.successMessage.Length > 0)
        {
            <div class='alert alert-success alert-dismissible fade show' role='alert'>
                <strong>@Model.successMessage</strong>
                <button type='button' class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        }

        <form method="post" enctype="multipart/form-data">
            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">ID</label>
                <div class="col-sm-8">
                    <input readonly class="form-control-plaintext" value="@Model.Product.Id"/>
                </div>
            </div>
            
            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Name</label>
                <div class="col-sm-8">
                    <input class="form-control" asp-for="ProductDTO.Name" />
                    <span asp-validation-for="ProductDTO.Name" class="text-danger"></span>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Brand</label>
                <div class="col-sm-8">
                    <input class="form-control" asp-for="ProductDTO.Brand" />
                    <span asp-validation-for="ProductDTO.Brand" class="text-danger"></span>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Description</label>
                <div class="col-sm-8">
                    <textarea class="form-control" asp-for="ProductDTO.Description"> </textarea>
                    <span asp-validation-for="ProductDTO.Description" class="text-danger"></span>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Category</label>
                <div class="col-sm-8">
                    <select class="form-select" asp-for="ProductDTO.Category">
                        @foreach (var category in Enum.GetValues(typeof(Product.Category)))
                        {
                            <option value="@category">@category</option>
                        }
                    </select>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Gender</label>
                <div class="col-sm-8">
                    <select class="form-select" asp-for="ProductDTO.Gender">
                        <option value='Male'>Male</option>
                        <option value='Female'>Female</option>
                    </select>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Price</label>
                <div class="col-sm-8">
                    <input class="form-control" asp-for="ProductDTO.Price" />
                    <span asp-validation-for="ProductDTO.Price" class="text-danger"></span>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label"></label>
                <div class="col-sm-8">
                    <img src="/products/@Model.Product.ImageFileName" width="150" />
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Name</label>
                <div class="col-sm-8">
                    <input class="form-control" asp-for="ProductDTO.ImageFile" />
                    <span asp-validation-for="ProductDTO.ImageFile" class="text-danger"></span>
                </div>
            </div>

            <div class="row mb-3">
                <label class="col-sm-4 col-form-label">Created At</label>
                <div class="col-sm-8">
                    <input readonly class="form-control-plaintext" value="@Model.Product.CreatedAt.ToString("MM/dd/yyyy")" />
                </div>
            </div>

            <div class="row mb-3">
                <div class="offset-sm-4 col-sm-4 d-grid">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
                <div class="col-sm-4 d-grid">
                    <a class="btn btn-outline-primary" href="/Admin/Products/Index" role="button">Cancel</a>
                </div>
            </div>

        </form>
    </div>
</div>

ProductDTO

public class ProductDTO
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Brand { get; set; }

    public string? Description { get; set; }
    [Required]
    public string Category { get; set; }

    public Product.Category ProductCategory { get; set; }
    [Required]
    public string Gender { get; set; }
    [Required]
    public double Price { get; set; }
    [Required]
    public IFormFile? ImageFile { get; set; }
}

Product
班级:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Brand { get; set; }

    public string Description { get; set; }

    public Category ProductCategory { get; set; }
    public enum Category
    {
        Sneakers,
        Ugg,
        Heels,
        Boots
    }

    public string Gender { get; set; }
    public double Price { get; set; }
    public string ImageFileName { get; set; }
    public DateTime CreatedAt { get; set; }
}
c# asp.net-mvc
1个回答
0
投票

事实证明,只需从 Edit.cshtml.cs 中删除此 if 语句即可解决整个问题

        //if (!ModelState.IsValid)
        //{
        //    errorMessage = "Please complete all required fields";
        //    return;
        //}
© www.soinside.com 2019 - 2024. All rights reserved.