I'm building a .NET MVC project, and have a situation where the Create form for a model is not accepting user input, and still submitting 0 even when I enter a different value. As you can see below, the field can't accept the value 0, so this invalidates the model.
Relevant model field:
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 and POST Controller:
// 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);
}
View:
<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>
EDIT: Changing to public int? QTY does not work - the same issue persists, only the error is now the the QTY field is required, as the default HTML value is null instead of 0. THe input field simply won't retain the value.