为什么我的 Inventory.cshtml 没有从控制器或模型接收或发送任何内容。在 ASP.NET MVC 中

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

我正在尝试修复所有可能出现错误的命名空间中的所有拼写错误。但此时我没有从控制台或终端收到任何错误,因此我找不到问题。问题是我正在尝试从 Inventory.cshtml 中的模型和控制器接收错误或消息。

这是我在实体

中第一个
Product.cs

的代码
using System.ComponentModel.DataAnnotations;

namespace SportsCapstone.Entities
{
    public class Product
    {
        [Key]
        public int Id { get; set; }

        // public byte[] Image { get; set; } // Storing image as byte array

        [Required(ErrorMessage = "Product is required.")]
        [MaxLength(20, ErrorMessage = "Max 20 characters allowed")]
        public string ProductName { get; set; }

        [Required(ErrorMessage = "Brand is required.")]
        [MaxLength(20, ErrorMessage = "Max 20 characters allowed")]
        public string ProductBrand { get; set; }

        [Required(ErrorMessage = "Quantity should not be empty")]
        [Range(1, int.MaxValue, ErrorMessage = "Quantity Must be atleast 1.")]
        public int Quantity { get; set; }

        [Required(ErrorMessage = "Type of Product is required.")]
        [MaxLength(20, ErrorMessage = "Max 20 characters allowed")]
        public string TypeOfProduct { get; set; }

        [Required(ErrorMessage = "Type of Age is required.")]
        [Range(1, 60, ErrorMessage = "Age should not be more than 60")]
        public string AgeRange { get; set; }
    }
}

这是我的

AppDbContext.cs

using Microsoft.EntityFrameworkCore;

namespace SportsCapstone.Entities
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options) { }
        ... 
        public DbSet<Product> Products { get; set; } // Add this line

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            ....
            // Configure the Product entity
            modelBuilder.Entity<Product>()
                .Property(p => p.ProductName)
                .IsRequired();

            modelBuilder.Entity<Product>()
                .Property(p => p.ProductBrand)
                .IsRequired(); // Example for Brand

            modelBuilder.Entity<Product>()
                .Property(p => p.Quantity)
                .IsRequired(); // Example for Quantity

            modelBuilder.Entity<Product>()
                .Property(p => p.TypeOfProduct)
                .IsRequired(); // Example for Quantity
            modelBuilder.Entity<Product>()
                .Property(p => p.AgeRange)
                .IsRequired(); // Example for Quantity

            // modelBuilder.Entity<Product>()
            //         .Property(p => p.Image)
            //         .IsRequired(); // Add this line if you want to ensure the Image property is required

            // Continue adding other configurations as necessary...

            base.OnModelCreating(modelBuilder);
        }

    }
}

我的下一个代码是 InventoryController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SportsCapstone.Models; // This should be your models namespace
using SportsCapstone.Entities; // Keep if you need to reference Product

namespace SportsCapstone.Controllers // Corrected namespace
{
    [Authorize]
    public class InventoryController : Controller
    {
        private readonly AppDbContext _dbContext;

        public InventoryController(AppDbContext appDbContext)
        {
            _dbContext = appDbContext;
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(InventoryItem model) // Change to InventoryItem
        {
            if (ModelState.IsValid)
            {
                // If needed, convert InventoryItem to Product here
                var product = new Product
                {
                    ProductName = model.ProductName,
                    ProductBrand = model.ProductBrand,
                    Quantity = model.Quantity,
                    TypeOfProduct = model.TypeOfProduct,
                    AgeRange = model.AgeRange
                };

                await _dbContext.Products.AddAsync(product);
                await _dbContext.SaveChangesAsync();

                ViewBag.Message = "Product created successfully!";
                return RedirectToAction("Index"); // Adjust as needed
            }

            return View(model); // Return the view with validation errors
        }
    }
}

最后是我的 InventoryItem.cs

using System.ComponentModel.DataAnnotations;

namespace SportsCapstone.Models
{
    public class InventoryItem
    {
        [Required(ErrorMessage = "Product name is required.")]
        [MaxLength(20, ErrorMessage = "Max 20 characters allowed.")]
        public string ProductName { get; set; }

        [Required(ErrorMessage = "Product brand is required.")]
        [MaxLength(20, ErrorMessage = "Max 20 characters allowed.")]
        public string ProductBrand { get; set; }

        [Required(ErrorMessage = "Quantity is required.")]
        [Range(1, int.MaxValue, ErrorMessage = "Quantity must be a positive number.")]
        public int Quantity { get; set; } // Changed to int

        [Required(ErrorMessage = "Type of product is required.")]
        [MaxLength(20, ErrorMessage = "Max 20 characters allowed.")]
        public string TypeOfProduct { get; set; }

        [Required(ErrorMessage = "Age range is required.")]
        [Range(5, 20, ErrorMessage = "Age range must be between 5 and 20.")]
        public string AgeRange { get; set; }

        // [Required(ErrorMessage = "Image is required.")]
        // public IFormFile Image { get; set; } // For file uploads
    }
}

现在我正在尝试在

Views/ Dasboard / Inventory.cshtml

中创建一个创建函数
                @if (@ViewBag.Message != null)
                {
                    <div class="d-flex align-items-center justify-content-center w-100" style="color: green">
                        @ViewBag.Message
                    </div>
                }
                <form asp-controller="Inventory" asp-action="Create" method="post" enctype="multipart/form-data"
                    class="inv-cp-ppqty">
                    <div class="image">
                        <label for="imageUpload">
                            <svg id="imageLabel" width="16" height="16" viewBox="0 0 16 16" fill="none"
                                xmlns="http://www.w3.org/2000/svg">

                            </svg>
                            <img id="imagePreview"
                                style="display: none; max-width: 100%; height:100%; object-fit: cover; border-radius: 10px;" />
                        </label>
                        @* <input asp-for="Image" type="file" id="imageUpload" name="Image" required
                        onchange="previewImage(event)" /> *@

                        @* <span asp-validation-for="Image" class="text-danger"></span> *@

                        @* <img src="" alt=""> *@
                    </div>
                    <div class="fill-inv">
                        <div class="inp-inv">
                            <input asp-for="ProductName" type="text" placeholder="Product Name" />
                            <span asp-validation-for="ProductName" class="text-danger"></span>

                        </div>
                        <div class="inp-inv">
                            <input asp-for="ProductBrand" type="text" placeholder="Product Brand" />
                            <span asp-validation-for="ProductBrand" class="text-danger"></span>
                        </div>
                        <div class="inp-inv">
                            <input asp-for="Quantity" type="number" placeholder="Quantity" min="1" />
                            <span asp-validation-for="Quantity" class="text-danger"></span>
                        </div>
                        <div class="inp-inv">
                            <select asp-for="TypeOfProduct" id="typeOfProduct" class="form-control">
                                <option value="" disabled selected> Type of Product </option>
                                <option value="Cloth"> Cloth </option>
                                <option value="Pants"> Pants </option>
                                <option value="Accessories"> Accessories </option>
                                <option value="SportsGear"> Sports Gear </option>
                                <!-- Add more options as needed -->
                            </select>
                            <span asp-validation-for="TypeOfProduct" class="text-danger"></span>

                        </div>
                        <div class="inp-inv">
                            <select asp-for="AgeRange" id="ageRange" class="form-control">
                                <option value="" disabled selected> Age </option>
                                <option value="Kids"> -18 </option>
                                <option value="Adults"> 18+ </option>
                                <!-- Add more options as needed -->
                            </select>
                            <span asp-validation-for="AgeRange" class="text-danger"></span>

                        </div>
                        <button type="submit" class="button-type">
                            <h5> Create Item </h5>
                        </button>
                    </div>
                </form>

但我没有在控制器或模型中接收任何内容或发送任何内容...有人可以告诉我这是关于文件名或命名空间还是什么?我找不到任何问题,因为我没有收到任何错误或 Inventory.cshtml 中的消息

c# asp.net asp.net-mvc
1个回答
0
投票

首先,您需要更改您对

AgeRange
的选择,如下所示,因为您对此属性的验证必须在5到20之间。否则,模型验证将始终为假:

<select asp-for="AgeRange" id="ageRange" class="form-control">
    <option value="" disabled selected> Age </option>
    <option value="6"> 6 </option>
    <option value="7"> 7 </option>
    <option value="8"> 8 </option>
    <!-- Add more options as needed -->
</select>

那么你的视图名称是

Inventory.cshtml
,如果你不返回特定名称的视图,它将返回与操作名称相同的视图名称。也就是说你将返回到Create.cshtml。改变你的行动如下:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(InventoryItem model) // Change to InventoryItem
{
    if (ModelState.IsValid)
    {
        //...
        return RedirectToAction("Index"); // Adjust as needed
    }

    return View("Inventory", model); //return model with correct view name
}
© www.soinside.com 2019 - 2024. All rights reserved.