Need some advice on the correct approach for the next scenario.
I have three model classes:
namespace App.Models
{
public partial class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
public partial class Department
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int CompanyID { get; set; }
public Company Company { get; set; };
}
public partial class User
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int Department { get; set; }
public Department Department { get; set; };
}
}
When I access the Create view of the UserController
, I have a combobox to select the DepartmentID
.
The problem is that the list is too big. I would like to add within the view, a list to select the Company
. And in the Department
combobox, only the Department
s within the selected Company
should appear.
Any advice on the correct way to achieve this? I already know how to filter the Department
s by Company
within the view bag.
But I don't know how to make the change within the view and send the filter to the controller.
Thanks in advance.
Any advice on the correct way to achieve this? I already know how to filter the Departments by Company within the view bag.
But I don't know how to make the change within the view and send the filter to the controller
Well, first of all load your compay within your view. All you need to do is, query your company object and bind it into ViewBag. You can do as following:
ViewBag.Companies = _context.Companies.ToList();
Within the view, you should have following code:
<div class="form-group">
<label asp-for="CompanyId" class="control-label"></label>
<select asp-for="CompanyId" class="form-control" onchange="getDepartments(this.value)">
<option value="">Select Company</option>
@foreach (var company in ViewBag.Companies)
{
<option value="@company.ID">@company.Name</option>
}
</select>
</div>
Now, in order to load department based on selected company, you should get the company Id and then call a API for getting the department based on the company Id passed. Use ajax request to implement that.
You can do as following:
<div class="form-group">
<label asp-for="DepartmentId" class="control-label"></label>
<select asp-for="DepartmentId" id="departmentDropdown" class="form-control">
<option value="">Select Department</option>
</select>
</div>
Script:
<script>
function getDepartments(companyId) {
$.ajax({
url: '/User/GetDepartments',
type: 'GET',
data: { companyId: companyId },
success: function (data) {
$('#departmentDropdown').empty();
$.each(data, function (i, department) {
$('#departmentDropdown').append($('<option>').text(department.name).attr('value', department.id));
});
}
});
}
</script>
Controller:
public IActionResult GetDepartments(int companyId)
{
var departments = _context.Departments.Where(d => d.CompanyID == companyId).ToList();
return Json(departments);
}
Note: Make sure your ajax request URL point to your controller accordingly.