pius joshua

pius joshua

  • NA
  • 29
  • 6k

How To Pass Values From Controller To A TextBox Using Ajax

Mar 20 2023 1:50 PM

Hello, I am trying to Pass a Dropdown item from View to Controller and return value to a textbox. I have this

 //Dropdown value.. when an item is selected it goes to the controller to get the value and display it on a textbox
<select asp-for="ItemName" asp-items="ViewBag.item" class="ItemId">
<option value="" selected disabled>---Stock Items---</option>
</select>
//My Json code from Controller
public JsonResult GetAmountFromItem(int ItemId)
{
var ac = (from c in cdc.Stock
where c.ID == ItemId
select c).FirstOrDefault();
return Json(ac);
}
//I want the value to be displayed on this textbox
<input asp-for="Available" class="form-control Avail"  readonly />
<script type="text/javascript">
$(document).ready(function () {
GetAmountFromItem();
})
$(".ItemId").change(function () {
GetAmountFromItem();
});
var GetAmountFromItem = function () {
$.ajax({
url: '@Url.Action("GetAmountFromItem","Stock")',
type: 'GET',
data: {
ItemId: $('.ItemId').val(),
},
success: function (data) {
var avail = $('.Avail').val();
//I am now stock Here... how do I get it done..
$(data).each(
function (index, item) {
$('.ItemId').append('<option value="' + item.ItemID + '">' + item.item + '</option>')
});
},
error: function () {
}
});
}
</script>

Thank you for your precious time ... I trully appreciate..


Answers (3)