krishna_v
krishna_v

Reputation: 1511

HtmlHelper function to populate dropdown

I am trying to populate a dropdown control in ASP.NET MVC. I have a table named City and i am getting the records from this table to populate through entity data. I have used the ViewBag to add dynamically. However it throws a compilation error.

Code

- View

<h4>City through db</h4>
@Html.DropDownList(cities, "Select City");

Controller

public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            ActionFilterdbEntities db = new ActionFilterdbEntities();
            var cities = db.Cities;
            ViewBag.cities = new SelectList(cities, "Id", "CityName");
            return View();
        }
    }

Model

   [Table("City")]
    public class clCity
    {

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

    }
}

Db

CREATE TABLE [dbo].[City] (
    [Id]       INT           NOT NULL,
    [CityName] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Upvotes: 0

Views: 55

Answers (4)

Shahzad Khan
Shahzad Khan

Reputation: 530

@Html.DropDownList("cities", ViewBag.cities as SelectList,"Select City")

please use above code.

Upvotes: 1

Basanta Matia
Basanta Matia

Reputation: 1562

How about like this,

 @{
   SelectList cities = ViewBag.cities;
  }
 @Html.DropDownList("YourDropDownId", cities, "Select City")

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

Your View should look like:

<h4>City through db</h4>
@Html.DropDownList("YourInputId", (SelectList)ViewBag.cities, "Select City")

First argument is a string that will renter as id and name attributes of select tag.

Upvotes: 2

Rey
Rey

Reputation: 4002

You have to construct the dropdown like this:

@Html.DropDownList("nameOfTheField", (SelectList)ViewBag.cities, "Select city");

If you are putting this dropdown in a form and lets suppose you have a model like this:

public class SearchModel
{
    public int CityId { get; set; }
    //etc
}

then you would set the code like below:

@Html.DropDownList("CityId", (SelectList)ViewBag.cities, "Select city");

Upvotes: 2

Related Questions