DropDownList MVC C#

Я хочу создать dropdownlist, но борюсь с тем, как я отображаю его.

У меня есть следующий код.

Контроллер

            var trader = new DisplayTradersAttachedToCategoryViewModel
            {
                Description = data.Description,
                Id = data.Id,
                BusinessName = traders.Select(x => new BusinessNameViewModel { BusinessName = x.BusinessName, Id = x.Id }),
                Categories = _service.GetCategories().Select(x => new DropDownViewModel {Id = x.Id, Description = x.Description }).OrderBy(x=>x.Description)
            };

DisplayTradersAttachedToCategoryViewModel

public class DisplayTradersAttachedToCategoryViewModel
{
    public int Id { get; set; }
    public string Description { get; set; }

    [UIHint("BusinessNameDisplayTemplate")]
    public IEnumerable<BusinessNameViewModel> BusinessName { get; set; }

    [UIHint("DropDownEditorTemplate")]
    public IEnumerable<DropDownViewModel> Categories { get; set; }
}

DropDownViewModel

public class DropDownViewModel
{
    public int Id { get; set; }
    public string Description { get; set; }
}

DropDownEditorTemplate

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Internal.ViewModels.Controller.DropDownViewModel>>" %>
<table class="aligncenter">
  <tr class="tRow left"><%
    if (Model != null)
    {%>
      <td>
        <%=Html.DropDownList("Category", Model.)%> 
      </td><%
    }%>                        
  </tr>
</table>

Я не знаю то, что я предназначен для обеспечения в DropDownList или если я на самом деле делаю его корректный.

ОБНОВЛЕНИЕ

Контроллер

            var trader = new DisplayTradersAttachedToCategoryViewModel
            {
                Description = data.Description,
                Id = data.Id,
                BusinessName = traders.Select(x => new BusinessNameViewModel { BusinessName = x.BusinessName, Id = x.Id }),
                Categories = _service.GetCategories().Select(x => new SelectListItem() {Text = x.Description, Value = x.Id.ToString(), Selected = true})
            };

DisplayTradersAttachedToCategoryViewModel

    public int Id { get; set; }
    public string Description { get; set; }

    [UIHint("BusinessNameDisplayTemplate")]
    public IEnumerable<BusinessNameViewModel> BusinessName { get; set; }

    public IEnumerable<SelectListItem> Categories { get; set; }

    public int Category { get; set; }

    public string Button { get; set; } 

DeleteCategoryAttachedToTraders.aspx

using (Html.BeginForm("DeleteCategoryFromTradersAttachNewCategory", "Controller",FormMethod.Post))
    <%=Html.DropDownList("Categories")%>

Контроллер

[HttpPost]
            public ActionResult DeleteCategoryFromTradersAttachNewCategory(DisplayTradersAttachedToCategoryViewModel displayTradersAttachedToCategoryViewModel)
            {
                if (displayTradersAttachedToCategoryViewModel.Button == "Back to List") return RedirectToAction("ViewCategories");

            //Update traders with new category
            //delete category

            //if (_service.DeleteCategory((int)deleteCategoryViewModel.Id))
            //{
            //    return RedirectToAction("ViewCategories");
            //}

            return View("DeleteCategoryAttachedToTraders", displayTradersAttachedToCategoryViewModel);
        }

Когда я получаю доступ к контроллеру через Кнопку отправки, ничто не хранится в DisplayTradersAttachedToCategoryViewModel. Что я делаю неправильно?

Заранее спасибо за любую справку.

Clare

1
задан ClareBear 29 July 2010 в 12:48
поделиться

3 ответа

Спасибо ŁukaszW.pl / ajay_whiz за вашу помощь :-) В конце я использовал смесь обоих ответов:

Контроллер

Categories = _service.GetCategories(id).Select(x => new SelectListItem {Text = x.Description, Value = x.Id.ToString()}) 

DisplayTradersAttachedToCategoryViewModel

public IEnumerable<SelectListItem> Categories { get; set; }

DeleteCategoryAttachedToTraders.aspx

<%=Html.DropDownList("Category", Model.Categories)%> 
0
ответ дан 2 September 2019 в 22:39
поделиться

вы можете попробовать преобразовать его в (IEnumerable ) , т.е.

<%=Html.DropDownList("Category", (IEnumerable<SelectListItem>)Model.Categories)%> 

-или-

создать свойство модели типа SelectList и вы можете инициализировать его как

new SelectList(Categories.ToList(), "ID", "Description");
0
ответ дан 2 September 2019 в 22:39
поделиться

Попробуйте так:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Tameside.Internal.ViewModels.BuyWithConfidence.DropDownViewModel>>" %>
 <select>
     <% foreach(var category in Model.Categories) { %>
         <option value="<%= Html.Encode(category.Id) %>"><%= Html.Encode(category.Name %></option>
     <% } %>
 </select>

конечно Id и Name - это просто члены из моей головы. Используйте те, которые находятся в вашем классе категории.

2
ответ дан 2 September 2019 в 22:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: