简体   繁体   中英

How to get data from database and binding it dropdownlist

I'm filling list with country objects and I want to bind it dropdownlist with its id.But I want to show it with CountryName property. When I save the data it should go with CounrtyId property. There is a relation with book and country Country_CountryID is field of Book in database. How can I do that.

Models

 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; }

    }

Controller

[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();
    }

View

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Book</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.BookCheckOutDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BookCheckOutDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BookCheckOutDate, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.BookReturnDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BookReturnDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BookReturnDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>

    //Should come CountryName DropDownlist

}

Edit

In order to include the CountryID on book creation, you should include it in your Book model and use proper attributes to mark it as ForeignKey for the Country property on Book .

Then use it

@Html.DropDownListFor(model => model.CountryID, (IEnumerable<SelectListItem>)ViewBag.countrynames)

This way, you could bind it the same way as all other properties

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

If this does not work out of the box, you may load the specified country object by ID before saving the book.

Original

You want to populate a dropdown list, so your target cshtml is something along the line

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

As you can see, ViewBag.countrynames needs to be a list of SelectListItem , so in code behind you should assign

ViewBag.countrynames = countries.Select(x => new SelectListItem() { Value = x.CountryID.ToString(), Text = x.CountryName });

This way, the country name is visible in the resulting html page and the country id is the internal representation of the selected value

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);
    }

Now on view, you can cast this back like

 List<Country> countries =(List<Country>)ViewBag.Countries;

and then iterate through each item.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM