Search code examples
c#.net-coreasp.net-core-mvcasp.net-core-tag-helpers

Getting null value from select list(dropdownList)


Trying to get the Id of a selected item. But I am getting null value from it.

This is my view for creating a room where to select room type

<select asp-for="RoomType" asp-items="@(new SelectList(@ViewBag.roomType, "Id", "Type"))" class="form-control">
    <option>--Select--</option>
</select>

This is my models

public class RoomModel
{
    public int Id { get; set; }
    public string RoomName { get; set; }
    public RoomTypeViewModel RoomType { get; set; }
    public float Price { get; set; }
}
public class RoomTypeViewModel
{
    public int Id { get; set; }
    public string Type { get; set; }
}

Controller

[HttpGet]
public IActionResult CreateRoom()
{
    ViewBag.roomType = _context.RoomType.ToList();
    return View();
}

Solution

  • You should have of the item you want to put on the dropdown list like this.

    Controller.cs

    public class RoomController : Controller
    {
         private readyonly RoomTypeContext _contextRoomType;
    }
    
    public RoomController(RoomTypeContext contextRoomType)
    {
         _contextRoomType = contextRoomType;
    }
    
    public IActionResult Create()
    {
         List<RoomType> roomTypes = new List<RoomType>();
         roomTypes = (from room in _contextRoomType.roomTypes select room).ToList();
         roomTypes.Insert(0, new RoomType { });
         ViewBag.ListOfRoomTypes = roomTypes;
    }
    

    View.cshtml

    <select asp-for="RoomType" 
            class="form-control form-control-sm" 
            asp-items="@(new SelectList(@ViewBag.ListOfRoomTypes , "Id","Type"))">
    </select>