1

I need a DropDownList in page so I try this way:

Action:

[HttpGet]
public ActionResult GetPoint() {

  ...
  List<SelectListItem> zooms = new List<SelectListItem>();
    for (int i = 0; i <= 21; i++) {
      if (i == 9)
        zooms.Add(new SelectListItem() { Selected = true, Text = i.ToString(), Value = i.ToString() });
      else
        zooms.Add(new SelectListItem() { Selected = false, Text = i.ToString(), Value = i.ToString() });
            }
  model.myselectlist = zooms;
  ...

  return View(model);
}

And in View:

@Html.DropDownListFor(model => model.Zoom, Model.myselectlist , new { @class = "dropdown" })

So as I expected we have a DropDownList with the 9 is Selected Item.

But In the same View I need another DropDown So this is my implementation:

[HttpGet]
public ActionResult GetPoint() {

  ...

  List<SelectListItem> places = new List<SelectListItem>();
  places.Add(new SelectListItem() { Text = "NY", Value = "NY", Selected = false });
  places.Add(new SelectListItem() { Text = "CA", Value = "CA", Selected = false });
  places.Add(new SelectListItem() { Text = "TX", Value = "TX", Selected = false });
  places.Add(new SelectListItem() { Text = "NH", Value = "NH", Selected = true });
  places.Add(new SelectListItem() { Text = "NV", Value = "NV", Selected = false });
  model.myselectlistII = places;

  ...

  return View(model);
}

And in View I have:

@Html.DropDownListFor(model => model.Place, Model.myselectlistII , new { @class = "dropdown" })

So As you see I have a list that the NH Item has selected = true.

And I expect a dropdown list that the NH selected but that not happend and allways the first item selected.

In view I have a weird behavior, I debug the code in the end of the Action and in the start of @Html.DropDownListFor line in view page, every things is OK, but after this line I check again Model.myselectlistII the selected Item has changed and all items have Selected property with false, I don't understand what happened? where is the problem? why the first DropDownFor did not change any thing but the second one change my list? what is your suggestion?

Saeid
  • 13,224
  • 32
  • 107
  • 173
  • Did you set any value to your model field `Place` (for example, in the constructor or somewhere else)? If this is the case, it will override the `Selected` field of your list... – Samuel Caillerie Dec 31 '12 at 10:52
  • @SamuelCaillerie your right, actually I don't set any thing, and I must set the default value. – Saeid Dec 31 '12 at 11:29
  • @SamuelCaillerie So please post your answer, for next refer – Saeid Dec 31 '12 at 11:35
  • That's not really an answer, just a guess since I don't know what is in your ActionResult `GetPoint()` and in your model `model`, but as your `@Html.DropDownListFor()` is based on the field `model.Place`, if this field is initialized with something, this will override your `Selected` values in `model.myselectlistII`... – Samuel Caillerie Dec 31 '12 at 11:42

5 Answers5

0

Samuel Caillerie is correct. You are using DropDownListFor which binds your properties Zoom and Place to the select list. Whatever the value of these properties is what will be selected when the view renders. Haven't found a good peice of documentation on this but here is another stack overflow post to help back that up:

asp.net mvc 3 pre-select Html.DropDownListFor not working in nerd dinner

Community
  • 1
  • 1
Ben Tidman
  • 2,129
  • 17
  • 30
0

What I did in one of my projects and was kind of useful, was to develop 2 more overload for
DropDownListFor which accept selectedValue.

namespace MyMvcApplication.Helpers
{
    public static class ExtensionMethods
    {
        public static MvcHtmlString DropDownListFor<TModel, TProperty>
                             (this HtmlHelper<TModel> helper,
                              Expression<Func<TModel, TProperty>> expression,
                              string selectedValue,
                              IEnumerable<SelectListItem> selectList,
                              string optionLabel,
                              object htmlAttributes)
        {
            if (string.IsNullOrEmpty(selectedValue))
                selectedValue = string.Empty;
            if (selectList != null)
            {
                foreach (SelectListItem sli in selectList)
                {
                    if (sli.Value.ToLower().Trim() == selectedValue.ToLower().Trim())
                    {
                        sli.Selected = true;
                        break;
                    }
                }
            }
            else 
            { 
                selectList = new List<SelectListItem>() 
                                  { new SelectListItem() 
                                          { Text = "", Value = "", Selected = true }
                                  };
            }
            return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
        }


        public static MvcHtmlString DropDownListFor<TModel, TProperty>
                             (this HtmlHelper<TModel> helper,
                              Expression<Func<TModel, TProperty>> expression,
                              string selectedValue,
                              IEnumerable<SelectListItem> selectList,
                              string optionLabel,
                              IDictionary<string, object> htmlAttributes)
        {
            if (string.IsNullOrEmpty(selectedValue))
                selectedValue = string.Empty;
            if (selectList != null)
            {
                foreach (SelectListItem sli in selectList)
                {
                    if (sli.Value.ToLower().Trim() == selectedValue.ToLower().Trim())
                    {
                        sli.Selected = true;
                        break;
                    }
                }
            }
            else 
            { 
                selectList = new List<SelectListItem>() 
                                  { new SelectListItem() 
                                          { Text = "", Value = "", Selected = true } 
                                  };
            }
            return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
        }

    }
}

So in Views, I can pass a string as selectedValue to DropDownListFor, like:

@using MyMvcApplication.Helpers

@Html.DropDownListFor(model => model.MyData,
                               "Default Value for DropDownList", //Or Model.MySelectedValue
                               Model.MySelectList, null, null)
Tohid
  • 6,175
  • 7
  • 51
  • 80
0

Please take care if there is QUERY STRING with same name , it will override that behavior, Not sure about HIDDEN FIELDS with same name

i.e.

DropDownListFor will use the value of Query String of DinnerID if found Blockquote

0

The solution for this problem is simpler that we all think...

All we need to do, when return the view from the controller, is set the property on the view model for the element that the dropdown is bound to - i.e: model.Zoom = 'NH' for example

this way when we do this

@Html.DropDownListFor(model => model.Zoom, Model.myselectlist , new { @class = "dropdown" })

the HtmlHelper will automatically pick up the default value to display on the DropDownList

simples!

Hope it may help you and all the others - like me! - that have lost a lot of time searching for a solution for this apparent issue.

EdsonF
  • 2,719
  • 3
  • 30
  • 34
0

Check it out guys!!! Super static functional lazy way to select/choose/bind dropdownlistfor mvc razor bootstrap style ;) as a bonus go plug french Or english descriptions!!! yours to improve but you will easily get the idea. Have fun! MightyMart...

              <div class="form-group">
                    <label>@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Quel est votre niveau d'expertise" : "What is your skill level")</label>
                    @if (Model.ClientLevel == null)
                    {
                        <select class="form-control" name="ClientLevel">
                            <option selected value="0">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Choisir un niveau" : "Choose a level")</option>
                            <option value="1">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Débutant" : "Beginner")</option>
                            <option value="2">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Intermédiaire" : "Intermediate")</option>
                            <option value="3">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Advanced" : "Advanced")</option>
                            <option value="4">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Expert" : "Expert")</option>
                            <option value="5">@(HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Autre" : "Other")</option>
                        </select>
                    }
                    else
                    {

                        List<SelectListItem> listItems = new List<SelectListItem>();
                        listItems.Add(new SelectListItem() { Text = "Choose a level", Value = "Choose a level"});
                        listItems.Add(new SelectListItem() { Text = "Beginner", Value = "Beginner" });
                        listItems.Add(new SelectListItem() { Text = "Intermediate", Value = "Intermediate"});
                        listItems.Add(new SelectListItem() { Text = "Advanced", Value = "Advanced"});
                        listItems.Add(new SelectListItem() { Text = "Expert", Value = "Expert"});
                        listItems.Add(new SelectListItem() { Text = HttpContext.Current.Session["culture"].ToString().Equals("fr-CA") ? "Autre" : "Other", Value = "Other"});

                        @Html.DropDownListFor(m => m.ClientLevel, listItems, new { @class = "form-control" })
                    }
                </div>