Blazor WASM仓库管理应用:如何根据选中SKU自动显示对应单位?
Blazor WASM 自动填充商品单位实现方案
实现思路
监听InputSelect的选择变化事件,根据选中的SKU从预加载的SKUModel列表中匹配对应单位,自动赋值给itemModel.Unit,让只读的InputText同步显示单位。
具体步骤
- 拆分InputSelect绑定:将原
@bind-Value拆分为Value绑定和onchange事件,触发自定义方法更新单位 - 编写单位更新逻辑:通过选中的SKU在
skus列表中匹配对应模型,将其单位属性赋值给itemModel.Unit - 修正DOM ID冲突:原
InputNumber的id与单位输入框重复,改为Quantity避免冲突
修改后的完整代码
<EditForm Model="itemModel" OnSubmit="HandleSubmit" class="modal-body"> <div class="mb-3"> <label for="SKU" class="form-label">SKU</label> <InputSelect Value="@itemModel.Name" @onchange="(e) => UpdateUnit(e.Value?.ToString())" class="form-select" aria-label="Default select example"> @foreach (var item in skus) { <option value="@item.SKU" id="@item.SKU">@item.SKU</option> } </InputSelect> </div> <div class="mb-3"> <label for="Unit" class="form-label">Unit</label> <InputText @bind-Value="@itemModel.Unit" class="form-control" id="Unit" readonly></InputText> </div> <div class="mb-3"> <label for="Quantity" class="form-label">Quantity</label> <InputNumber @bind-Value="@itemModel.Quantity" min="1" step="any" class="form-control" id="Quantity"></InputNumber> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </EditForm>
对应的C#逻辑代码:
ItemModel itemModel = new ItemModel(); List<SKUModel> skus = new List<SKUModel>(); private void UpdateUnit(string selectedSku) { if (!string.IsNullOrEmpty(selectedSku)) { var matchedSku = skus.FirstOrDefault(s => s.SKU == selectedSku); itemModel.Unit = matchedSku?.Unit ?? string.Empty; } else { itemModel.Unit = string.Empty; } } private void HandleSubmit() { // 此处实现提交逻辑:将itemModel添加到List<ItemModel>并发送至API }
注意事项
- 确保
skus列表在模态框打开前已通过API加载完成,可在加载完成前禁用InputSelect避免空引用异常 - 若业务中存在重复SKU,需根据实际需求调整匹配规则(如使用
First或自定义筛选逻辑)
内容的提问来源于stack exchange,提问作者Patryk
相关产品推荐
相关产品推荐

