c# - .NET MVC 查看表单输入值不接受用户输入
问题描述
我正在构建一个 .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>
编辑:更改为公共 int?QTY 不起作用 - 同样的问题仍然存在,只是错误是现在需要 QTY 字段,因为默认的 HTML 值是 null 而不是 0。输入字段根本不会保留该值。
解决方案
您的绑定不正确[Bind("InventoryID,Quantity,BinID,ProductID")] Inventory inventory
。你应该做这样的事情:[Bind("InventoryID,QTY")] Inventory inventory
.
实际上,当您提交表单时,它将发送一个字典对象,然后 Bind 类将查看您的对象(在本例中为库存)和发送的字典之间是否有任何匹配。
如果您的 Inventory 对象具有其他属性,您可以将它们绑定到。
推荐阅读
- javascript - 单元测试事件处理程序是否一个接一个地调用promise(同步)
- postman - 如何为邮递员(表单数据)中的特定字段传递空数组?
- azure - 无法更改逻辑应用上的身份验证帐户
- google-bigquery - 数据流 SQL 嵌套 JSON 架构面临不明确的字段引用
- python - if *var* == *int*: var 是变量而 int 是数字的代码有什么问题?
- mysql - 无法在mysql的日期时间列中查询空值
- python - 基于 Pandas 中列和行值的关联关系值
- wpf - WPF XAML 无法加载文件或程序集“AssemblyName,PublicKeyToken=null”或其依赖项之一。该系统找不到指定的文件
- sql - 根据条件替换部分字符串 SQL
- python - 从变量中获取变量名