I am trying to get to grips with MVC and trying to populate a strongly typed dropdown list. I intend to have many dropdown controls on the index page and to keep things tidy I would like to use a different model for each dropdown and then have all these with the home index model.
When building the application I get the error "ViewModels.HomeIndex.TrackModel.get returned null."
When I set a breakpoint I can see the TrackModel is not empty, however the TrackId and TrackName are. I guess it is this that is causing the issue.
Anyone more familure with MVC see what may be wrong.
In my controller I have
public class HomeController : Controller
{
public ActionResult Index()
{
TrackModel tm = new TrackModel();
tm.Tracks = PopulateTracks();
return View(new HomeIndex());
}
[HttpPost]
public ActionResult Index(TrackModel tm)
{
tm.Tracks = PopulateTracks();
var selectedItem = tm.Tracks.Find(p => p.Value == tm.TrackId.ToString());
if (selectedItem != null)
{
selectedItem.Selected = true;
ViewBag.Message = "Track: " + selectedItem.Text;
ViewBag.Message += "\\TrackName: " + tm.TrackName;
}
return View(tm);
}
private static List<SelectListItem> PopulateTracks()
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["AiryDb"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT UserId, TrackName FROM UploadData";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["TrackName"].ToString(),
Value = sdr["UserId"].ToString()
});
}
}
con.Close();
}
}
return items;
}
}
}
HomeIndex Model I have
public class HomeIndex
{
public TrackModel TrackModel { get; set; }
}
TrackModel I Have
public class TrackModel
{
public List<SelectListItem> Tracks { get; set; }
public int? TrackId { get; set; }
public int? TrackName { get; set; }
}
My razor view
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>
Tracks:
</td>
<td>
@Html.DropDownListFor(m => m.TrackModel.TrackId, Model.TrackModel.Tracks, "Please select")
</td>
</tr>
<tr>
<td>
Track Name:
</td>
<td>
@Html.TextBoxFor(m => m.TrackModel.TrackName)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}