akhter says:
<script type=
"text/javascript"
>
$(document).ready(
function
() {
$(
"#Item"
).change(
function
() {
var
itemId= $(
"#Item"
).val();
GetItemUnitPrice(itemId);
});
});
You are selecting id #Item which is wrong the correct Id is #select2-3.
Please refer below sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult getItemUnitPrice(int itemId)
{
NORTHWINDEntities entities = new NORTHWINDEntities();
decimal? UnitPrice = entities.Products.Single(model => model.ProductID == itemId).UnitPrice;
return Json(UnitPrice, JsonRequestBehavior.AllowGet);
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@Html.DropDownList("Item", new SelectList(new List<SelectListItem> {
new SelectListItem{Text="Please Select", Value="0"},
new SelectListItem{Text="Chai", Value="1"},
new SelectListItem{Text="Chang", Value="2"},
new SelectListItem{Text="Aniseed Syrup", Value="3"}}, dataValueField: "Value", dataTextField: "Text"),
new { @class = "form-control", @id = "select2-3" })
<hr />
<input type="text" style="text-align:right;" readonly="readonly" id="txtUnitPrice" value="0.00" name="UnitPrice" class="form-control" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#select2-3").change(function () {
var itemId = $("#select2-3").val();
GetItemUnitPrice(itemId);
});
});
function GetItemUnitPrice(itemId) {
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
url: '/Home/getItemUnitPrice', data: { itemId: itemId },
success: function (data) {
$("#txtUnitPrice").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("There is some problem to get the Unit Price.");
}
});
}
</script>
</body>
</html>
Screenshot