Article: ASP.Net MVC: Using jQuery Select2 Plugin with DropDownList
How to populate multiple TextBoxes from database using entity framwork and mvc
my code only populate two TextBoxes
<form id="newBasket">
<div class="form-group row">
<div class="col-sm-6">
<label>Select Product</label>
@Html.DropDownListFor(m => m.productname, new SelectList(Model.ProductSelectListItem, "Value", "Text"), new { @id = "ddlproduct", @class = "form-control", @onchange = "getProductData(this)" })
</div>
<div class="col-sm-3">
<label>Qty</label>
@Html.TextBoxFor(m => m.qty, new { @id = "txtqty", @class = "form-control", @Value = "1", @style = "font-weight:bold; text-align:center" })
</div>
<div class="col-sm-3">
<label>Price</label>
@Html.TextBoxFor(m => m.salesprice, new { @id = "txtprice", @class = "form-control", @Value = "0", @readonly = "readonly", @style = "background-color:white; font-weight:bold; text-align:center" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-8">
<label>Product Description</label>
<input id="txtproductdescription" name="txtproductdescription" type="text" class="form-control" readonly="readonly" style="background-color:white" />
</div>
<div class="col-sm-4">
<br />
<input id="btnaddtolist" type="button" class="btn btn-success" value="Add To List" />
</div>
</div>
@Html.HiddenFor(m => m.proid, new { @id = "txtproid" })
@Html.HiddenFor(m => m.unitcost, new { @id = "txtcost" })
@Html.HiddenFor(m => m.basketid, new { @id = "txtbasketid", @Value = ViewBag.otp })
@Html.TextBoxFor(m => m.basketid, new { @id = "txtbasketid", @Value = ViewBag.otp })
@Html.TextBoxFor(m => m.unitcost, new { @id = "txtcost1" })
@Html.TextBoxFor(m => m.proid, new { @id = "txtproid1" })
</form>
/*Select product by id */
function getProductData() {
var selected_val = $('#ddlproduct').find(":selected").attr('value');
$.ajax({
type: "GET",
url: "/CashSales/GetProductDataByID",
data: "id=" + selected_val,
success: function (data) {
if (data.length > 0) {
$("#txtproductdescription").val(data[0].ProductDescription);
$("#txtproid1").val(data[0].proid);
$("#txtcost1").val(dada[0].UnitCost);
$("#txtprice").val(data[0].SalesPrice);
}
else {
$('#txtprice').val('0');
$('#txtproductdescription').val('');
$('#txtcost').val('0');
$('#txtprice').val('0');
}
}
});
}
This two are not populating.
$("#txtcost1").val(dada[0].UnitCost);
$("#txtprice").val(data[0].SalesPrice);
public JsonResult GetProductDataByID(int id)
{
List<Product> prolist = PopulateProducts();
return Json(prolist.Where(x => x.proid == id), JsonRequestBehavior.AllowGet);
}
// Get Branch from Database.
private static List<Product> PopulateProducts()
{
List<Product> prolist = new List<Product>();
using (POSContext db = new POSContext())
{
var p = db.Products.ToList();
foreach (var pro in p)
{
prolist.Add(new Product
{
proid = pro.proid,
ProductDescription = pro.ProductDescription,
UnitCost = pro.UnitCost,
SalesPrice = pro.SalesPrice
});
}
}
return prolist;
}