。NET MVC视图表单输入值不接受用户输入

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

我正在构建.NET MVC项目,并且存在以下情况:模型的“创建”表单不接受用户输入,即使输入其他值也仍然提交0。如下所示,该字段不能接受值0,因此会使模型无效。

相关模型字段:

public class Inventory
    {
        [Key]
        [Display(Name = "Inventory ID")]
        public int InventoryID { get; set; }
        [Required]
        [Range(1, int.MaxValue, ErrorMessage = "Please enter a value larger than 0")]
        public int QTY { get; set; }

GET和POST控制器:

// GET: Inventories/Create
        public IActionResult Create()
        {
            ViewData["BinID"] = new SelectList(_context.Bins, "BinID", "BinName");
            ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductDescription");
            return View();
        }

        // POST: Inventories/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("InventoryID,Quantity,BinID,ProductID")] Inventory inventory)
        {
            if (ModelState.IsValid)
            {
                _context.Add(inventory);
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException ex)
                {
                    // send message to view
                    ModelState.AddModelError(string.Empty, "An inventory for this bin and product already exists");
                    ViewData["BinID"] = new SelectList(_context.Bins, "BinID", "BinName", inventory.BinID);
                    ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductDescription", inventory.ProductID);
                    return View(inventory);
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["BinID"] = new SelectList(_context.Bins, "BinID", "BinName", inventory.BinID);
            ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductDescription", inventory.ProductID);
            return View(inventory);
        }

查看:

<div class="form-group">
    <label asp-for="QTY" class="control-label"></label>
    <input asp-for="QTY" class="form-control" />
    <span asp-validation-for="QTY" class="text-danger"></span>
</div>

编辑:更改为public int? QTY不起作用-同样的问题仍然存在,只是错误是现在需要QTY字段,因为默认HTML值是null而不是0。输入字段根本不会保留该值。

c# .net model-view-controller
1个回答
0
投票

您的装订不正确[Bind("InventoryID,Quantity,BinID,ProductID")] Inventory inventory。您应该执行以下操作:[Bind("InventoryID,QTY")] Inventory inventory

实际上,当您提交表单时,它将发送一个字典对象,然后Bind类将查看您的对象(在这种情况下为清单)与发送的字典之间是否存在匹配项。

如果您的清单对象具有其他属性,则可以将它们与绑定。

© www.soinside.com 2019 - 2024. All rights reserved.