Hello Guys I'm having hard time in displaying data that are being call in ajax into the view. I'm new with ajax. When I'm searching Id I want to auto fill other fields.
thank you for replying
CodePudding user response:
Below is a work demo, you can refer to it.
AutoFilledModel:
public class AutoFilledModel
{
[Key]
public string ProjectId { get; set; }
public string Region { get; set; }
}
AutoFilledController:
public class AutoFilledController : Controller
{
public IActionResult Index()
{
List<SelectListItem> projectidlist = new()
{
new SelectListItem { Value = "178290", Text = "178290" },
new SelectListItem { Value = "192834", Text = "192834" },
new SelectListItem { Value = "194364", Text = "194364" }
};//you can use your way to pass dropdownlist
//assigning SelectListItem to view Bag
ViewBag.projectidlist = projectidlist;
return View();
}
[HttpPost]
public IActionResult GetDropDownList(string id)
{
var autoFilledModels= new List<AutoFilledModel>()
{
new AutoFilledModel() {ProjectId="178290",Region="Nordic"},
new AutoFilledModel() {ProjectId="192834",Region="Luzon"},
new AutoFilledModel() {ProjectId="194364",Region="Luzon45"}
};
// you can get data from database too
var result = autoFilledModels.FirstOrDefault(m => m.ProjectId == id);
return Json(result);
}
}
Index view:
@model AutoFilledModel
<div >
<label asp-for="ProjectId" ></label>
<select asp-for="ProjectId" class ="form-control" asp-items="ViewBag.projectidlist"></select>
</div>
<div >
<label asp-for="Region" ></label>
<input asp-for="Region" />
<span asp-validation-for="Region" ></span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/jscript">
$(function() {
$("#ProjectId").change(function() {
var selectedid = $('option:selected').val();
if (selectedid > 0) {
$.ajax({
url: "/AutoFilled/GetDropDownList",
data: {
id: selectedid
},
type: "Post",
dataType: "Json",
success: function(result) {
document.getElementById('Region').value = result.region;
},
error: function() {
}
});
}
});
});
</script>
result: