Поле со списком asp.net mvc

1

У меня есть datatable в Index.cshtml scaffold-ed из Bus.cs

    public class Bus
    {
        public int BusID { get; set; }

        public int BusOwnerID { get; set; }

        public string RegistrationNo { get; set; }
    }

На индексной странице мне нужно включить выпадающий список с BusOwnerID и BusOwnerName из BusOwner.cs

    public class BusOwner
    {
        public int BusOwnerID { get; set; }

        public string BusOwnerName { get; set; }

        public string Moblie { get; set; }

        public string EmailID { get; set; }
    }

В контроллере у меня есть следующее:

    public ActionResult Index()
    {
        ViewBag.Genres = db.BusOwners.Select(i => new SelectListItem { Value = i.BusOwnerID.ToString(), Text = i.BusOwnerName });

        return View(db.Buses.ToList());
    }

В представлении index.cshtml мне нужен dropdownbox с BusOwnerID и BusOwnerName. При выборе мне нужно отобразить детали автобусов, которые попадают под выбранный BusOwnerID.

Я попробовал следующее

    @Html.DropDownListFor(model => model.BusOwnerID, new SelectList(ViewBag.Genres), "Choose... ")

Но возникает ошибка.

        CS1061: 'System.Collections.Generic.IEnumerable<RaspberryPi.Models.Bus>' does not contain a definition for 'BusOwnerID' and no extension method 'BusOwnerID' accepting a first argument of type 'System.Collections.Generic.IEnumerable<RaspberryPi.Models.Bus>' could be found (are you missing a using directive or an assembly reference?)

Index.cshtml

    @model IEnumerable<RaspberryPi.Models.Bus>

    @{
        ViewBag.Title = "Buses";
    }

    <div class="btn-group">
        <a href="/Buses/Create" class="btn btn-primary btn-lg">Create New</a>

    </div>

    @*@Html.LabelFor(model => model.BusOwnerID)
    @Html.DropDownListFor(model => model.SelectRegionId, Model.Regions, "Choose... ")


    @Html.DropDownList("drop", new SelectList(ViewBag.Genres));*@

    <div id="Ttable" style="background:#f5f5f5;position:relative;width:100%;height:25%;">
        <table id="example" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>@Html.DisplayNameFor(model => model.RegistrationNo)</th>
                    <th>@Html.DisplayNameFor(model => model.BusTypes)</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayNameFor(model => model.RegistrationNo)
                        </td>
                        <td>
                            @Html.DisplayNameFor(model => model.BusTypes)
                        </td>
                        <td>
                            <div class="btn-group">
                                <button type="button" class="btn-primary btn-xs" onclick="location.href = '/Buses/Details/@item.BusID';"><span class="glyphicon glyphicon-th"></span></button>
                                <button type="button" class="btn-success btn-xs" onclick="location.href = '/Buses/Edit/@item.BusID';"><span class="glyphicon glyphicon-pencil"></span></button>
                                <button type="button" class="btn-danger btn-xs" onclick="location.href = '/Buses/Delete/@item.BusID';"><span class="glyphicon glyphicon-remove"></span></button>
                            </div>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

Как я могу это достичь?

Пожалуйста, помогите, спасибо.

Теги:
asp.net-mvc
asp.net-mvc-5
drop-down-menu

2 ответа

1

Сделайте это так

Составьте список BusOwner на вашем представлении перед созданием Dropdown

var busOwnerList=BusOwner.GetAll(); //Make static method in your class to return all owner

Теперь

@Html.DropDownListFor(model => model.BusOwnerID, new SelectList(busOwnerList, "BusOwnerID", "BusOwnerName") as SelectList, "Choose... ")
0

Ошибка указывает, что в вашей модели нет свойства BusOwnerId. Также ошибка говорит нам, что модель имеет тип IEnumerable.

В вашем случае BusOwnerId присутствует только в одном экземпляре Bus а не в наборе автобусов. Таким образом, есть два варианта.

1 Верните одну шину в представление, как модель

вместо:

return View (db.Buses.ToList());

Пытаться

return View(db.Buses.FirstOrDefault());

Который вернет первую шину из базы данных.

2 Или вы можете прокручивать каждую запись шины в модели и отображать выпадающий список для каждой шины:

foreach(var bus in Model)
{
     @Html.DropDownListFor(x => bus.BusOwnerID, new SelectList(ViewBag.Genres), "Choose... 
}

обратите внимание, что в lamda я привязываюсь к x => bus.busOwnerId вместо x => x.BusOwnerId потому что x.BusOwnerId указывает, что BusOwnerId является свойством в модели. Это не потому, что модель представляет собой коллекцию.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню