I have project's class
public class Project
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
then, it's displayed using dropdownlist
@Html.DropDownListFor(model => model.Id,
new SelectList(Model.Projects, "Id", "Name", Model.Id),
"-- Select --",
new { @class = "form-control" })
If I select a project, I can get the Id and Name, but how to get the description?
<script>
$(function () {
$('#id').change(function () {
alert('id = ' $('#Id').val() ', name = ' $('#Id :selected').text() ', description = ' ???);
});
});
</script>
CodePudding user response:
There are two ways
If list of projects are very large you will have to create API and use ajax to get a description.
In javascript get list of project from model and find a description
<script>
var projects = @Html.Raw(Json.Encode(Model.Projects));
console.log(JSON.stringify(projects)); //only for test
$(function () {
$('#id').change(function () {
let id= $('#Id').val();
let description = null;
let name = null;
projects.forEach((item) => {
if (item.Id === id) {
name= item.Name;
description= item.Description;
break;
}
});
alert('id = ' id ', name = ' name ', description = ' description);
});
}
</script>