Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to bind a dropdown in mvc4?
Posted

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<modelobjects> pl = new List<modelobjects>();

Code in Modelobjects (Another model) :

public class Modelobjects
{

//property of items inside dropwdon list

public string Port_Name { get; set; }
}
 
Share this answer
 
v2
Check this out.


Dropdownlistfor in mvc[^]

It really helps
 
Share this answer
 
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"" })
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900