Click here to Skip to main content
11,580,580 members (69,334 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: MVC4
how to bind a dropdown in mvc4?
Posted 14-Jan-13 19:46pm
PftADev317
Rate this: bad
good
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();
portret.pl = 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 portret.pl)
{
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; }
}
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Check this out.


Dropdownlistfor in mvc[^]

It really helps
  Permalink  
Rate this: bad
good
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"" })
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 1,088
1 Sergey Alexandrovich Kryukov 750
2 Abhinav S 638
3 Suvendu Shekhar Giri 433
4 F-ES Sitecore 420


Advertise | Privacy | Mobile
Web03 | 2.8.150603.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