I know there are many answers to this type of question, I have read them all and still cannot work this out.
I have a dropdown I am populating in the controller using a SelectList and transferring using a viewbag. I have simplified it in the following, just 0,1 & 2, with the same value for Text & Value.
I really want text of 'None', 'Weekly' and 'Monthly', and tried viewmodel values of 1 and Weekly, neither gets displayed.
The viewmodel is currently passing an initial value of 1 (I have tried passing both string and int values, and also checked it is passing 1 using EditorFor rather than DropDownFor), but the dropdown displays the first value 0, not the model value.
I have got this working elsewhere, but the SelectList is populated from a db table as follows. In this case the model passes a value for ID and the correct initial value for Aircraft is displayed.
var nAir = (from n in db.Handicaps
orderby n.Aircraft
where n.ClubsID == ClubsID
select n).ToList();
ViewBag.Aircraft = new SelectList(nAir, "ID", "Aircraft");
But when I populate the list manually, the model value is ignored.
I am obviously missing something, but cannot work out what it is. I could set up a table for EmailFreq and do it like the example above but there are only 3 values in the dropdown so it seems overkill.
Controller :
ViewBag.EmailFreq = new SelectList(new List<SelectListItem>
{
new SelectListItem { Value = "0", Text = "0"},
new SelectListItem { Value = "1", Text = "1" },
new SelectListItem { Value = "2", Text = "2" }
}, "Value", "Text");
var profile = new ClubProfileEdit
{
ClubID = ClubsID,
ClubName = Session["ClubName"].ToString(),
EmailFreq = existProfile.EmailFreq.ToString()
};
return View(profile);
The view:
<div class="form-group">
@Html.LabelFor(model => model.EmailFreq, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.EmailFreq, new SelectList(ViewBag.EmailFreq, "Value", "Text"), new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.EmailFreq, "", new { @class = "text-danger" })
</div>
</div>
The Viewmodel:
namespace OAcontest.ViewModels
{
public class ClubProfileEdit
{
public int ID { get; set; }
public int ClubID { get; set; }
public string ClubName { get; set; }
public string EmailFreq { get; set; }
}
}