Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
1845
MVC Helper - Set initial selected item by value
posted

How do I set the initially selected item in a combobox from MVC, given the value?  I tried using the "SelectedValues" property like this: http://pastebin.com/M4kSyY5P

...but nothing was selected, despite there being a row in the datasource with an id of 104.  I also tried the same method using a list of int instead of string, but no luck.  I also tried the "text" property, but this also doesn't do anything.

The "SelectedIndex" property does work exactly as expected, so worse-case scenario I can just get index by value, but it would be good to know either way.

Parents
  • 24497
    posted

    Hi Josh,

    Besides an option mentioned by Tsvetelina, you may initialize selection on server using initial value in field or Selected item in SelectListItem collection. Below are examples:

    View aspx file:

    <%= Html.Infragistics().Combo("Combo1").DataSource(Model.GetMyStringData()).Render() %>
    <%= Html.Infragistics().ComboFor(m => Model.Combo2, Model.ListItems).Render()%>
    <%= Html.Infragistics().Combo(Model.Combo9Model) %>

    Model cs file:

     public class MyComboModel
     {
      private string _combo1 = "DJO4";
      public string Combo1 { get { return this._combo1; } set { this._combo1 = value; } }

      public string[] Combo2 { get; set; }

      private ComboModel _combo3;
      public ComboModel Combo3
      {
       get
       {
        if (this._combo3 == null)
        {
         this._combo3 = new ComboModel();
         this._combo3.DataSource = new string[] { "Item1", "Item2", "Item3" };
         this._combo3.SelectedValues = new string[] {"Item2"};
        }
        return this._combo3;
       }
      }
      public List<SelectListItem> ListItems
      {
       get
       {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem { Text = "Swimming", Value = "1" });
        items.Add(new SelectListItem { Text = "Cycling", Value = "2", Selected = true });
        items.Add(new SelectListItem { Text = "Running", Value = "3" });
        return items;
       }
      }
     }

Reply Children
No Data