创建具有增删改查功能的 ASP.NET 应用程序,但无法创建新产品,因为 ModelState.IsValid 为 false

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

我正在编写一个具有 CRUD 功能的 ASP.NET MVC Web 应用程序,当我单击创建按钮时,我的

ModelState.IsValid
始终返回 false。当我添加一些调试时,它显示在创建此表时未选择包含另一个表中的类别列表(这是我的产品模型的外键)的下拉列表,并且它表示需要
categoryId
。请问谁能帮我解决这个问题吗?

这些是我的模型类:

public class Product
{
    [Key]
    public int ProductID { get; set; }
    
    [Display(Name = "Product Name")]
    public string ProductName { get; set; }

    [Display(Name = "Category")]
    [ForeignKey("Category")]
    public int CategoryID { get; set; }

    [Display(Name = "Unit of Measurement")]
    public string Unit { get; set; }

    public decimal Price { get; set; }

    public Category Category { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    
    [Display(Name = "Category Name")]
    public string CategoryName { get; set; }

    [Display(Name = "Description")]
    public string Description { get; set; }

    public ICollection<Product> Products { get; set; }
}

这是我的控制器

public IActionResult Create()
{
    ViewBag.CategoryID = new SelectList(_context.Category, "CategoryID", "CategoryName");
    return View();
}

// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
// add debuggers to the Create method
public async Task<IActionResult> Create([Bind("ProductID,ProductName,CategoryID,Unit,Price")] Product product)
{
    if (!ModelState.IsValid)
    {
        // Log each error in the ModelState
        var errorList = ModelState
                             .Where(x => x.Value.Errors.Count > 0)
                             .ToDictionary(kvp => kvp.Key,
                                           kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray());

        // For debugging: place a breakpoint here and inspect errorList
        foreach (var error in errorList)
        {
            Debug.WriteLine($"Key: {error.Key}, Errors: {string.Join(", ", error.Value)}");
        }

        // Re-populate the CategoryID dropdown before returning the view
        ViewBag.CategoryID = new SelectList(await _context.Category.ToListAsync(), "CategoryID", "CategoryName", product.CategoryID);

        return View(product);
    }

    // Proceed with adding the product to the database
    _context.Add(product);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}

我的创作观:

<div class="form-group">
    <label asp-for="CategoryID" class="control-label"></label>
    <select asp-for="CategoryID" asp-items="ViewBag.CategoryID" class="form-control"></select>
</div>

我期望当我单击“创建新产品”时,它会向我的数据库添加一个新产品,并在下拉列表中选择类别。

我尝试了调试和一切,确保数据库具有类别等。

FROM [Category] AS [c]
Key: Category, Errors: The Category field is required.
Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [c].[CategoryID], [c].[CategoryName], [c].[Description]
FROM [Category] AS [c]
c# .net asp.net-mvc asp.net-core entity-framework-core
1个回答
0
投票

“它说需要categoryId”和“在下拉列表中选择类别。”

我猜你可能会看到错误

Category  is required
。确保您已在下拉列表中选择了 CategoryID 。您可以尝试添加
?
,如下所示,以避免 ModelState.IsValid 为 false:

public Category? Category { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.