Hi nabilabolo,
Check the below code.
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Platform 1", Value = "1" });
items.Add(new SelectListItem { Text = "Platform 2", Value = "2" });
items.Add(new SelectListItem { Text = "Platform 3", Value = "3" });
items.Add(new SelectListItem { Text = "Platform 4", Value = "4" });
TempData["platform"] = items;
return View();
}
public JsonResult GetData(int id)
{
List<StudentList> plist = populateStudent();
return Json(plist.Where(p => p.list_id == id));
}
private static List<StudentList> populateStudent()
{
List<StudentList> list = new List<StudentList>();
list.Add(new StudentList { list_id = 1, Name = "Name 1", Age = 30, Address = "Address 1" });
list.Add(new StudentList { list_id = 2, Name = "Name 2", Age = 35, Address = "Address 2" });
list.Add(new StudentList { list_id = 3, Name = "Name 3", Age = 50, Address = "Address 3" });
return list;
}
public class StudentList
{
public int list_id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}
View
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function get_sbu() {
var id = $('#ddlCustomers').find(":selected").attr('value');
$.ajax({
type: "POST",
url: "/Home/GetData",
data: "id=" + id,
success: function (data) {
if (data.length > 0) {
$('#task').val(data[0].Age);
$('#task2').val(data[0].Address);
} else {
$('#task').val('');
$('#task2').val('');
}
}
});
}
</script>
Name:
<select id="ddlCustomers" onchange="get_sbu()">
<option value="0">Select</option>
<%foreach (var item in (List<SelectListItem>)TempData["platform"]) { %>
<option value='<%=item.Value%>'><%=item.Text%></option>
<% } %>
</select>
<br />
Age : <input type="text" id="task" /><br />
Address : <input type="text" id="task2" /><br />
Email Required? <input type="checkbox" id="isSelected" />
Screenshot
Use below code to populate Students from Database.
private static List<StudentList> populateStudent()
{
List<StudentList> list = new List<StudentList>();
var platform = db.tblStudent.ToList();
foreach (var item in platform)
{
list.Add(new StudentList
{
list_id = item.list_id,
Name = item.Name,
Age = item.Age,
Address = item.Address
});
}
return list;
}