Joseph Anderson
Joseph Anderson

Reputation: 4144

MVC DropDownListFor ViewData Selected Item

I am trying to get the selected value of a drop down list to default to 3600, if the value is 0. Unfortunately, the drop down defaults to the first option. I believe the selection fails because nothing in the list matches 0. Here is my code:

Controller method:

    public void GetTaskInterval(JMASettings model)
    {
        IList<SelectListItem> ilSelectList = new List<SelectListItem>();
        Dictionary<string, string> secondsDictionary = new Dictionary<string, string>();
        secondsDictionary.Add("Every Thirty Minutes", "1800");
        secondsDictionary.Add("Every Hour", "3600");
        secondsDictionary.Add("Every Three Hours", "10800");
        secondsDictionary.Add("Every Day", "86400");

        foreach (KeyValuePair<string, string> pair in secondsDictionary)
        {
            SelectListItem item = new SelectListItem();
            item.Text = pair.Key;
            item.Value = pair.Value;

            if (model.TaskInterval == 0 && item.Value.ToString() == "3600")
                item.Selected = true;

            if (item.Value == model.TaskInterval.ToString())
                item.Selected = true;

            ilSelectList.Add(item);
        }

        ViewData["TaskInterval"] = ilSelectList;
    }

.cshtml

@Html.DropDownListFor(model => model.JMASettings.TaskInterval, (IEnumerable<SelectListItem>)ViewData["TaskInterval"])

Upvotes: 0

Views: 2251

Answers (2)

Ali Adlavaran
Ali Adlavaran

Reputation: 3735

Use the SelectList and put the IEnumerable<SelectListItem> into it:

        Dictionary<string, string> secondsDictionary = new Dictionary<string, string>();
        secondsDictionary.Add("Every Thirty Minutes", "1800");
        secondsDictionary.Add("Every Hour", "3600");
        secondsDictionary.Add("Every Three Hours", "10800");
        secondsDictionary.Add("Every Day", "86400");

var itemlist = new SelectList(secondsDictionary, "Key" , "Value", 3600);

and in your view:

@Html.DropDownListFor(model => model.JMASettings.TaskInterval, itemlist , "Select one")

the default value has been set to 3600 but you can change it.

God luck !:)

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

If you want to set default value with DropDownListFor() helper you should understand that it is respect value of first argument model.JMASettings.TaskInterval in your case.

So you should just check that you put right value to this model property in your Controller.

Upvotes: 1

Related Questions