Reputation: 2209
I know this is very simple but new to Mvc. I will like to populate a dropdownbox with data from the GetDescription method such that the dropdown shows the Description and when selected the code is passed as the value.
How can I write the html piece?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public static List<Populate> GetDescription()
{
List<Populate> myInfor = new List<Populate>()
{
new Populate{Id=1,Description="Lagos", Code="lag"},
new Populate{Id=2,Description="Ibadan", Code="lba"},
new Populate{Id=3,Description="Akure", Code="Aku"},
new Populate{Id=4,Description="Ejigbo", Code="Eji"},
new Populate{Id=5,Description="Oshogbo", Code="Osh"}
};
return myInfor;
}
}
public class Populate
{
public int Id { get; set; }
public string Description { get; set; }
public string Code { get; set; }
}
Here is the html
*********************
@model PopulateDropDownList.Models.Populate
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.DropDownList(Model.id, Model.Description, "--Select One--")
</p>
Upvotes: 0
Views: 585
Reputation: 3479
You may also do it like that.
Modify a bit your code:
public static class Helper
{
public static List<SelectListItem> GetDescription()
{
List<Populate> myInfor = new List<Populate>()
{
new Populate{Id=1,Description="Lagos", Code="lag"},
new Populate{Id=2,Description="Ibadan", Code="lba"},
new Populate{Id=3,Description="Akure", Code="Aku"},
new Populate{Id=4,Description="Ejigbo", Code="Eji"},
new Populate{Id=5,Description="Oshogbo", Code="Osh"}
};
var result = new List<SelectListItem>();
var items = from n in myInfor
select new SelectListItem
{
Text = n.Description,
Value = n.Id.toString()
};
foreach (var item in items)
result.Add(item);
return result;
}
}
Than in your View: @using YourProject.Helper
@Html.DropDownList("AnyTextAsID", Helper.GetDescription())
Upvotes: 2
Reputation: 19
You could do this in your view:
@{
Dictionary<string, string> populate = new Dictionary<string, string>();
populate.Add("Lagos", "lag");
populate.Add("Ibadan", "lba");
populate.Add("Akure", "aku");
populate.Add("Ejigbo", "eji");
populate.Add("Oshogbo", "osh");
}
@Html.DropDownList("myinfo", new SelectList(populate.ToList(), "Value", "Key", "Lagos"), new { id = "Populate" })
Upvotes: 0