I'm having a problem in subtracting the amount inputted by the user to the current stock count. here is my code.
here is some of my code. I have a link in index of ItemReg
that will open the withdraw.cshtml
once click then, when the user put a value on the input box the value will be deducted to the database.
Controller
public IActionResult Withdraw(int? id, int quantity)
{
return View(_context.ItemRegs.Find(id));
}
public async Task<IActionResult> Withdraw([Bind("ItemId,Qty")] ItemReg itemReg,int? id, int quantity)
{
if (ModelState.IsValid) {
var itemreg = _context.ItemRegs.Find(id);
itemreg.Qty = itemreg.Qty - quantity;
_context.Update(itemReg);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(itemReg);
}
withdraw.cshtml
@model Intranet.Models.ItemReg
@{
ViewData["Title"] = "View";
}
<h4>ItemReg</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="View">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ItemId" />
<div class="form-group">
<label asp-for="Qty" class="control-label"></label>
<input name="quantity" asp-for="Qty" class="form-control"/>
<span asp-validation-for="Qty" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
You are using id as the source of your Find(id)
. Try passing itemReg.ItemId
in your Find(itemReg.ItemId)
as your hidden field is ItemId
<input type="hidden" asp-for="ItemId" />
which is binding in the model is not used, try using your model.Id
var itemreg = _context.ItemRegs.Find(itemReg.ItemId);
itemreg.Qty = itemreg.Qty - quantity;
_context.Update(itemReg);
Im not sure if this is a good practice but this answers my question.
public async Task<IActionResult> Withdraw([Bind("ItemId,Qty")] ItemReg itemReg,int quantity)
{
ViewBag.qty = quantity;
//if (ModelState.IsValid) {
var itemreg = _context.ItemRegs.Find(itemReg.ItemId);
itemreg.Qty = itemreg.Qty - ViewBag.qty;
itemReg.UserName = ViewBag.DisplayName;
itemreg.UserIP = HttpContext.Connection.RemoteIpAddress.ToString();
itemreg.UserDate = DateTime.Now.ToString("MM/dd/yyyy");
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
//}
//return View(itemReg);
}
I commented the if statement then add the int quantity in the argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.