ASP.NET MVC如何将下拉列表选中数据传递到Invoice表并完成更新
实现方案
1 修复下拉列表值无法存入Invoice表问题
问题原因
原视图中下拉框使用@Html.DropDownList( "Product", "Select")生成,控件name属性为Product,和模型InvoiceTb中存储商品信息的属性ListName名称不一致,MVC默认模型绑定无法匹配赋值,导致选中值无法入库。
修复步骤
控制器GET方法调整
将原SelectList构造改为带自定义属性的SelectListItem集合,用于存储商品单价供前端计算使用:
public ActionResult UpdateInvoice() { var getProduct = db.InventoryTbs.Select(p => new SelectListItem { // 如果需存储商品ID到InvoiceTb,此处Value改为p.PId.ToString(),同时和模型对应属性匹配即可 Value = p.PName, Text = p.PName, // 自定义属性存储商品单价 HtmlAttributes = new { data_price = p.PPrice.ToString() } }).ToList(); ViewBag.Product = getProduct; return View(); }
视图下拉框调整
改为强类型绑定,确保控件name和模型属性一致:
@Html.DropDownListFor(m => m.ListName, (IEnumerable<SelectListItem>)ViewBag.Product, "请选择", new { @class = "form-control", id = "ProductSelect" })
2 实现自动计算账单金额
视图控件调整
给数量、账单输入框增加唯一ID,账单字段设为只读避免手动修改:
<!-- 数量输入框 --> @Html.EditorFor(model => model.LQuantity, new { htmlAttributes = new { @class = "form-control", id = "QuantityInput" } }) <!-- 账单输入框 --> @Html.EditorFor(model => model.Bill, new { htmlAttributes = new { @class = "form-control", id = "BillInput", @readonly = "readonly" } })
增加前端计算脚本
在视图底部加入JS代码,监听商品选择和数量输入事件自动计算金额:
<script> document.addEventListener('DOMContentLoaded', function() { const productSel = document.getElementById('ProductSelect'); const quantityInput = document.getElementById('QuantityInput'); const billInput = document.getElementById('BillInput'); // 计算总金额方法 function calcTotal() { const price = parseFloat(productSel.options[productSel.selectedIndex].getAttribute('data-price')) || 0; const num = parseInt(quantityInput.value) || 0; billInput.value = (price * num).toFixed(2); } // 绑定触发事件 productSel.addEventListener('change', calcTotal); quantityInput.addEventListener('input', calcTotal); }); </script>
3 后端安全加固(必改)
前端计算的金额可被篡改,POST接口中需重新计算金额再入库,同时异常分支需要重新给ViewBag赋值避免下拉框无数据:
[HttpPost] public ActionResult UpdateInvoice(InvoiceTb idetail) { if (Session["User"] == null) { return RedirectToAction("Login"); } try { // 后端重新查询单价计算金额,避免前端篡改 var product = db.InventoryTbs.FirstOrDefault(p => p.PName == idetail.ListName); if (product != null) { idetail.Bill = product.PPrice * idetail.LQuantity; } db.InvoiceTbs.Add(idetail); db.SaveChanges(); return RedirectToAction("ShowInvoice"); } catch { // 异常返回时重新加载下拉框数据 var getProduct = db.InventoryTbs.Select(p => new SelectListItem { Value = p.PName, Text = p.PName, HtmlAttributes = new { data_price = p.PPrice.ToString() } }).ToList(); ViewBag.Product = getProduct; return View(idetail); } }
内容的提问来源于stack exchange,提问作者strk38
相关产品推荐
相关产品推荐

