如何从数据库中获取数据并将其绑定到下拉列表中

时间:2015-08-30 11:21:30

标签: asp.net asp.net-mvc

我填写了国家/地区对象列表,我想将其与其id绑定下拉列表。但我想用CountryName属性显示它。当我保存数据时,它应该与CounrtyId属性一起使用。与书籍和国家/地区有关系Country_CountryID是数据库中Book的字段。我怎么能这样做。

模型

for e in range (0, len(heightandweight),3):
    print(" ".join(heightandweight[e:e+3]))

控制器

 public class Country
    {
        [Key]
        public int CountryID { get; set; }

        public string CountryName { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        [DataType(DataType.Date)]
        [Required]
        public DateTime Holiday { get; set; }

        public string WeekendDayOne { get; set; }

        public string WeekendDayTwo { get; set; }
    }
 public class Book
    {

        public int BookID { get; set; }

        [Required]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        [DataType(DataType.Date)]
        public DateTime BookCheckOutDate { get; set; }


        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        [DataType(DataType.Date)]
        [Required]
        public DateTime BookReturnDate { get; set; }

        public Country Country { get; set; }

    }

查看

[HttpPost]
public ActionResult Create([Bind(Include = "BookID,BookCheckOutDate,BookReturnDate")] Book book)
    {
        if (ModelState.IsValid)
        {
            db.Books.Add(book);
            List<Country> countries = db.Countries.ToList();

            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(book);
    }

 // GET: Books/Create
    public ActionResult Create()
    {
        List<Country> countries = db.Countries.ToList();

        ViewBag.CountryName = countries;

        // I want to bind countries with a dropdownlist

        return View();
    }

2 个答案:

答案 0 :(得分:1)

修改

为了将CountryID包含在图书创建中,您应该将其添加到Book模型中,并使用适当的属性将其标记为Country属性Book@Html.DropDownListFor(model => model.CountryID, (IEnumerable<SelectListItem>)ViewBag.countrynames)

然后使用它

public ActionResult Create([Bind(Include = "BookID,BookCheckOutDate,BookReturnDate,CountryID")] Book book)

这样,你可以用与所有其他属性相同的方式绑定它

@Html.DropDownList("listname", (IEnumerable<SelectListItem>)ViewBag.countrynames)

如果这不是开箱即用的,您可以在保存图书之前按ID加载指定的国家/地区对象。

<强>原始

您想要填充下拉列表,因此您的目标cshtml就行了

SelectListItem

正如您所看到的,ViewBag.countrynames需要是ViewBag.countrynames = countries.Select(x => new SelectListItem() { Value = x.CountryID.ToString(), Text = x.CountryName }); 的列表,所以在代码背后你应该分配

if None not in d.viewvalues():

这样,国家/地区名称在生成的html页面中可见,国家/地区ID是所选值的内部表示

答案 1 :(得分:-1)

public ActionResult Create([Bind(Include = "BookID,BookCheckOutDate,BookReturnDate")] Book book)
    {
        if (ModelState.IsValid)
        {
            db.Books.Add(book);
            db.SaveChanges();
            List<Country> countries = db.Countries.ToList();
            //Put this 'countries' in ViewBag like 
            ViewBag.Countries = countries;
            //return RedirectToAction("Index");
        }
        return View(book);
    }

现在可以查看,你可以像

一样强制转换它
 List<Country> countries =(List<Country>)ViewBag.Countries;

然后遍历每个项目。

<select id="select1" >
   <option value='0'>--Select--</option>
   @foreach(var cnt in countries)
   {
   <option value='@cnt.Id'>@cnt.Name</option>
   }
</select>