如何使用具有多个值的 @Html.DropDownList



我有一个表MedicineIDMedicineNameprice

现在我有这个@Html.DropDownList由餐桌药填充。我想包含值 IDMedicineNameprice调用或在 jquery 中使用它。

目前我只能得到MedicineName

我的控制器:

 public ActionResult Create()
    {
        ViewBag.ClientID = new SelectList(db.Clients, "ClientID", "Surname");
        ViewBag.MedicineID = new SelectList(db.Medicines, "MedicineID", "MedicineName");
        return View();
    }

我的观点:

 @Html.DropDownList("MedicineID", ViewBag.MedicineID, htmlAttributes: new { @class = "form-control" })

脚本:

 $("#btnAdd").click(function () {
        var medname = $("#MedicineID option:selected").text()
        var qty = $("#myID").val()
        $("#tblList").append('<tr> <td>' +medname+ '</td>  <td>'+qty+'</td>  <td>   </td>  <td><a class="remove" href="#">del</a></td></tr>')
    })

尝试从控制器操作方法在下拉列表中发送格式化数据。你可以使用这样的东西:

    public ActionResult Create()
    {
            ViewBag.ClientID = new SelectList(db.Clients, "ClientID", "Surname");
           //modified code
            var medlist = db.Medicines.AsEnumrable().Select(x => new {Id = x.MedicineID, MedName = (x.Id + " "+ x.MedicineName +" "+ x.Price).ToString()});
            ViewBag.MedicineID = new SelectList(medlist, "ID", "MedName");
            return View();
        }

现在,您可以在下拉列表中看到药物的ID,名称和价格。您可以根据需要设置下拉列表的格式。您可以通过放置适当的字符串函数在脚本中提取数据。

你不能使用 @Html.DropDownList ,它只允许 2 个数据值:id 和文本。

相反,您可以使用@Html.NameFor@Html.IdFor来构建自己的下拉列表:

<select name="@Html.NameFor(Function(model) model.CityId)"
        id="@Html.IdFor(Function(model) model.CityId)">
    @For Each medicine In Model.Medicines
        @<option value="@medicine.MedicineId"
                 data-price="@medicine.price">
            @medicine.MedicineName
        </option>
    Next
</select>

不能在选择列表的每一行中存储 3 个值。它只有 ID 和文本。

您可以做的是更改调用 webapi 并使用从选择列表中获得的 id 请求其他数据。

最新更新