I can't find an example that suits my needs anywhere, so I'm asking you guys.
Im trying to populate a ListBox on my website with content from an SQL CE database.
I used Asp.Net MVC DropDownList Data Binding as an example to create my ListBox.
I have now hit a deadend and could use some help, here is what i got:
Index.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Headline</h2>
<% using (Html.BeginForm())
{ %>
<%= Html.ListBoxFor(x => x.SelectedItemId, new SelectList(Model.Items, "Value", "Text"))%>
<br /><input type="submit" value="Show" style="width: 72px" />
<% } %>
</asp:Content>
HomeController.cs
public ActionResult Index()
{
var model = new ItemsViewModel();
using (SqlCeConnection con = new SqlCeConnection(@"Data Source=|DataDirectory|\RSSdb.sdf;Persist Security Info=False"))
{
con.Open();
string cmdString = string.Format("SELECT Name, ID FROM TableIndex WHERE (Active = N'true')");
using (SqlCeCommand cmd = new SqlCeCommand(cmdString, con))
{
using (SqlCeDataReader dataRead = cmd.ExecuteReader())
{
model = new ItemsViewModel
{
Items = new[]
{
new SelectListItem { Value = "Foo", Text = "Foo" } ,
new SelectListItem { Value = "Bar", Text = "Bar" }
}
};
}
}
}
return View(model);
}
ItemsViewModel.cs
public class ItemsViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Now what i need is to have the code in HomeController.cs be something like this:
model = new ItemsViewModel
{
Items = new[]
{
While(dataRead.Read())
{
new SelectListItem { Value = dataRead["ID"], Text = dataRead["Name"] };
}
}
};
But this don't work, and i have no idea how else to do it, all help is appreciated.