Reputation: 437
I have a table Medicine
with column ID
,MedicineName
and price
Now I have this @Html.DropDownList
populated by the table medicine. I want to include the value ID
,MedicineName
and price
the call or use it in jquery.
currently I can only get the MedicineName
My controller:
public ActionResult Create()
{
ViewBag.ClientID = new SelectList(db.Clients, "ClientID", "Surname");
ViewBag.MedicineID = new SelectList(db.Medicines, "MedicineID", "MedicineName");
return View();
}
My view:
@Html.DropDownList("MedicineID", ViewBag.MedicineID, htmlAttributes: new { @class = "form-control" })
Script:
$("#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>')
})
Upvotes: 1
Views: 2047
Reputation: 2607
Try to send formatted data inside your dropdown from controller action method.You can use something like this:
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();
}
Now you are able to see id,name and price for your medicine inside dropdown. You can format dropdown as per your need. And you can extract your data in script by placing appropriate string functions.
Upvotes: 2
Reputation: 21585
You can't use @Html.DropDownList
, it only allows 2 data values: id and text.
Instead you can use @Html.NameFor
and @Html.IdFor
to build your own drop down:
<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>
Upvotes: 0
Reputation:
You cant store 3 values in each row of select list. It has only Id and Text.
What you can do is to onchange call a webapi and ask for additional data using id you get from select list.
Upvotes: 0