Click here to Skip to main content
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 20: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 215
1 George Jonsson 175
2 Kornfeld Eliyahu Peter 159
3 PIEBALDconsult 110
4 Richard MacCutchan 85
0 OriginalGriff 6,080
1 DamithSL 4,648
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,624
4 Sergey Alexandrovich Kryukov 3,294


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 21 Apr 2014
Copyright © CodeProject, 1999-2014
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