Click here to Skip to main content
11,931,104 members (59,734 online)
Rate this:
Please Sign up or sign in to vote.
See more: MVC4
how to bind a dropdown in mvc4?
Posted 14-Jan-13 20:46pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

If you are using Html.Dropdownlist(Name of the dropdown list,Values of dropdownlist).

Code in view :

@Html.DropDownList("portname", (IEnumerable<SelectListItem>)ViewData["items"], new { @class = "drpdwn" })

Code in Controller :


// create an object dl to access datatacess layer and get the dataset
Modelobj portret=new modelobj();
DAL dl = new DAL(); = dl.GetPortList();
List<selectlistitem>items = new List<selectlistitem>();
items = getitems(portret2);
ViewData["items"] = items;

public List<selectlistitem> getitems(Modelobj portret)
List<selectlistitem> items = new List<selectlistitem>();
foreach (var item in
items.Add(new SelectListItem
Text = Convert.ToString(item.Port_Name),
Value = Convert.ToString(item.Port_Name)
return items;
Code in Modelobj(Model Name):

public List pl = new List();

Code in Modelobjects (Another model) :

public class Modelobjects

//property of items inside dropwdon list

public string Port_Name { get; set; }
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Check this out.

Dropdownlistfor in mvc[^]

It really helps
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

In controller

private void fillAllDDL()
using (ExamEntities context = new ExamEntities())
var lstCourse = (from t in context.Courses
orderby t.Course_Name
select t).ToArray();

ViewBag.course = new SelectList(lstCourse, "Course_Id", "Course_Name");

In View
@Html.DropDownListFor(m => m.course, (SelectList)ViewBag.course, "--Select Course--", new { @Id = "ddlCourse", @width = "150px"" })

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.151126.1 | Last Updated 21 Apr 2014
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100