You asked how to set an input but the code is clearly designed to populate select options. I'm not sure what you are trying to do since your question is so very different than how the code actually works. Also, you did not provide the models so we have no idea what properties "ac" returns. Therefore, we do not know which property to assign to the input.
This is my best guess to answer your question.
Models
public class ItemVm
{
public string ItemName { get; set; }
public string Available { get; set; }
}
public class Stock {
public int ID { get; set; }
public string Name { get; set; }
}
Controller actions
[HttpGet]
public IActionResult Index()
{
List<SelectListItem> options = new List<SelectListItem>()
{
new SelectListItem("Item 1", "1"),
new SelectListItem("Item 2", "2"),
new SelectListItem("Item 3", "3"),
};
ViewBag.item = options;
return View();
}
[HttpGet]
public IActionResult GetAmountFromItem(int? ItemId)
{
//Mock data
List<Stock> items = new List<Stock>()
{
new Stock() {ID = 1, Name = "Stock 1" },
new Stock() {ID = 2, Name = "Stock 2" },
new Stock() {ID = 3, Name = "Stock 3" }
};
var ac = items.FirstOrDefault(i => i.ID == ItemId);
return Json(ac);
}
View
@model MvcDemo.Models.ItemVm
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<div>
<div>
<select asp-for="ItemName" asp-items="ViewBag.item" class="ItemId">
<option value="" selected disabled>---Stock Items---</option>
</select>
</div>
<div>
<input type="text" asp-for="Available" class="form-control Avail" readonly />
</div>
</div>
@section scripts {
<script>
$(".ItemId").change(function () {
GetAmountFromItem();
});
var GetAmountFromItem = function () {
$.ajax({
url: '@Url.Action("GetAmountFromItem","Stock")',
type: 'GET',
data: {
ItemId: $('.ItemId').val(),
},
success: function (data) {
$('.Avail').val(data.name);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
}