Home > OS >  ASP.NET MVC - Dropdown list depending on another dropdown list, with info coming from a ViewBag
ASP.NET MVC - Dropdown list depending on another dropdown list, with info coming from a ViewBag

Time:11-20

I am trying to figure out a way to make the dropdown list of Rooms depending on the dropdown list of departments in my view. I'm struggling to access the viewbag in javascript but I haven't found a way to access it. Any help is appreciated

My Controller ->

public ActionResult CreateActivity()
{
    ViewBag.Departments = departmentRepository.Collection;
    ViewBag.Rooms = roomRepository.Collection;
    return View();
}

My View ->

<div>
    <select asp-for="Department.DepartmentID" onchange="this.form.submit()">
        @foreach (Department d in ViewBag.Departments)
        {
            <option value="@d.DepartmentID">@d.DepartmentName</option>
        }
    </select>
</div>

<span asp-validation-for="Room.RoomName"></span>
<div>
    <select asp-for="Room.RoomID" >
        <option value="" disabled selected hidden>Vælg Lokale</option>
        @foreach (Room r in ViewBag.Rooms)
        {
            <option value="@r.RoomID">@r.RoomName</option>
        }
    </select>
</div>

Room Model ->

public class Room
{
    public int RoomID { get; set; }
    [Required(ErrorMessage = "Lokalenavn mangler")]
    [MaxLength(40)]
    public string RoomName { get; set; }
    [Required(ErrorMessage = "Afdelingsnavn mangler")]
    public Department Department { get; set; }
}

Department Model ->

public class Department
{ 
    public int DepartmentID { get; set; }
    [Required(ErrorMessage = "Afdelingsnavn mangler")]
    [MaxLength(40)]
    public string DepartmentName { get; set; }
}

I have tried to access the viewbag with javascript but I haven't been able to do it. Any help is appreciated

CodePudding user response:

inside CreateActivity actionresult, you can set the values of ViewBag.Departments and ViewBag.Rooms into JSON or delimited string (convert the collection to a JSON or delimited string). Then assign the ViewBag.Departments and ViewBag.Rooms to a hidden input type elements in your view. Use javascript to access the values from hidden input type elements. not a good solution but you can see other options from there.

  • Related