【问题标题】:Bind dropdown list from database从数据库绑定下拉列表
【发布时间】:2013-11-28 18:58:48
【问题描述】:

我一直在努力创建一个下拉列表,该列表将显示数据库中的国家/地区名称。 情况是: 我有一个控制器“AdvertisementController”、一个模型“AdvertisementModel”和一个视图“Create.cshtml”。 在视图中,我需要创建一个下拉列表,该列表将显示数据库中的国家/地区名称。

我知道创建 Viewmodel 是一件好事。但是我该怎么做呢? 一堆代码将不胜感激。 :)

我有以下代码,但它显示“空引用”错误。

视图模型:

 public class CommunicationViewModel
    {

        public string CategoryID { get; set; }
        public IEnumerable<SelectListItem> CategoryList { get; set; }
    }

型号:

public class CreateAdModel
    {
        [Required]
        [Display(Name = "Title")]
        public string Title { get; set; }

        [Required]
        [Display(Name = "Description")]
        [DataType(DataType.MultilineText)]
        public string Message { get; set; }

        [Required]
        [Display(Name = "Ad type")]
        public string AdType { get; set; }

        [Required]
        [Display(Name = "Ad category")]
        public string AdCategory { get; set; }

        public CommunicationViewModel categories { get; set; }


    }

控制器:

public ActionResult Index()
    {
        var query = db.AddCategory.Select(c => new SelectListItem
                                                 {
                                                     Value = c.ID.ToString(),
                                                     Text = c.Name
                                                 }
                                                 );
        var model = new CommunicationViewModel { CategoryList = query.AsEnumerable() };
        return View(model);
    }

剃须刀:

 @Html.DropDownListFor(m=>m.categories.CategoryID,Model.categories.CategoryList,"--Select one--")

【问题讨论】:

  • 尝试搜索“mvc dropdownlist”。像你一样的大量问题:)
  • 为您的绝妙想法干杯 Kasper..:)。我确实关注了你并发现了一些错误。猜我做错了..

标签: asp.net-mvc-3 drop-down-menu


【解决方案1】:

这可能会对您有所帮助。添加用户时下拉角色。很简单的教程

http://rtur.net/blog/post/2009/06/03/Quick-and-dirty-role-management-in-ASPNET-MVC.aspx

【讨论】:

  • 在页面底部下载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多