I have the following action method in my Tournament controller:
public ActionResult Edit(int id) {
EditTournamentViewModel viewModel = new EditTournamentViewModel {
Tournament = _tournamentService.GetTournamentByID(id),
TournamentDivisions = _divisionService.GetTournamentDivisions(id).ToList()
};
ViewBag.SportID = new SelectList(_sportService.GetSports(), "SportID", "Name");
ViewBag.CountryID = new SelectList(_countryService.GetCountries(), "CountryID", "Name");
return View(viewModel);
}
The two viewbag items are select lists which will be filled up. When I inspect the page with firebug the name of the SelectList for ViewBag.SportID is SportID, which is what I would expect. But I want the value that is selected there to be entered in the SportID property of the Tournament property in my viewModel. So the name should be Tournament.SportID.
I don’t understand how I can achieve this, I wasn’t able to change the SelectList’s name in Razor like this:
<div class="editor-field">
@Html.DropDownList("SportID", "Select a sport", new { name = "Tournament.SportID" } )
@Html.ValidationMessageFor(t => t.Tournament.Sport)
</div>
This is the code I have in my view:
<div class="editor-field">
@Html.DropDownList("SportID", "Select a sport")
@Html.ValidationMessageFor(t => t.Tournament.Sport)
</div>
A solution I could take is instead of having a Tournament property in my viewmodel, I could copy over the individual properties and then use automapper but I would like to hear if there is a fix without having to do that (unless of course what I am doing is considered very bad practice).
Did you try
?
(if you need the acual value of Tournament.SportId, for an update, for example, you can just look at the different constructors of SelectList and change it in your “ViewBag creation”)
CORRECTION :