Share via


Dropdown List Default Value Isn't Sticking to the Selected Value

Question

Monday, March 12, 2018 2:34 PM

I have multiple drop down list to filter the results on a table when the submit button is clicked. For 3 of them ,the selected value sticks after I press submit. However for one of the drop down lists bounces back to the default value. All the code is the same so I am not sure why they are acting differently. I want it so that when the submitted button is clicked the selected value is still selected. How do I go about this?

View:

using (Html.BeginForm())
{

<table class="table">
<tr>
<td>
Group
@Html.DropDownList("group", new SelectList(ViewBag.Groupcmb), "--Select--")
</td>

<td>
Principal
@Html.DropDownList("prin", new SelectList(ViewBag.Principalcmb), "--Select--")
</td>

<td>
OSR
@Html.DropDownList("osr", new SelectList(ViewBag.OSRcmb), "--Select--")
</td>

<td>
Status
@Html.DropDownList("status", new SelectList(ViewBag.Statuscmb), "--Select--")
</td>


<td>
Customer
@Html.DropDownList("customer", new SelectList(ViewBag.Customercmb), "--Select--")
</td>

<td>
<input type="submit" value="Search" onclick="loation.href='@Url.Action("Index", "Strategy")'" />
</td>
</tr>
</table>


}

Controller

  var groups = from g in db.Strategies
                                     select g;
                        var prins = from pr in db.Strategies
                                    select pr;
                        var osrs = from o in db.Strategies
                                   select o;
                        var statuss = from s in db.Strategies
                                      select s;

                        var customers = from c in db.Strategies
                                      select c;


                        ViewBag.Groupcmb = (from g in db.Strategies.Include(p) where g.Group != null
                                         select g.Group).Distinct();

                        ViewBag.Principalcmb = (from pr in db.Strategies.Include(p) where pr.Principal != null
                                             select pr.Principal).Distinct();

                        ViewBag.OSRcmb = (from o in db.Strategies.Include(p)
                        where o.OSR != null
                        select o.OSR).Distinct();

                        ViewBag.Customercmb = (from v in db.Strategies.Include(p)
                                          where v.Customer != null
                                          select v.Customer).Distinct();


                        ViewBag.Statuscmb = (from s in db.Strategies.Include(p) where s.Status != null
                                          select s.Status).Distinct();


                        ViewData["OSR"] = new SelectList(ViewBag.OSRcmb);
                        

                        //if all filters are null
                        if (group == null && stratvar == null && prin == null && osr == null && status == null && customer == null)
                        {
                            return View(db.Strategies.ToList());
                        }



                        if (prin != null && group != null && osr != null && status != null && customer != null)
                        //if (group != null)
                        {

                            prins = prins.Where(gpr => gpr.Principal.Contains(prin) && gpr.Group.Contains(group) && gpr.OSR.Contains(osr) && gpr.Status.Contains(status) && gpr.Customer.Contains(customer));
                            stratvar = null;
                            return View(prins.ToList());
                        }

Model

        public int StrategyId { get; set; }
        public string Customer { get; set; }
        public string Status { get; set; }
        public string OSR { get; set; }
        public string Principal { get; set; }
        public string Group { get; set; }

All replies (17)

Monday, March 19, 2018 8:42 AM ✅Answered

Hi jamiie,

@model IEnumerable<WebApplication2.Models.Strategy>

 

@{

    ViewBag.Title = "Index";

}

 

<h4>Index</h4>

Does that mean it is already a strongly type view?

Yes, it is a strong type view now, but it is not the point why you can't get work with your updated selected dropdown list value; 

Is there a way to do it without passing in a model?

Sir, in fact, i have answered the question in my post before.

ep.

Here is the full working code

        public ActionResult About(string MyUserName=null)// this is the key line code which pass the selected value of dropdownlist collection
        {
            List<SelectListItem> contactsListItems  = new List<Color> {
                new Color { ID=22, Name= "Color1" },
                new Color { ID=23, Name= "Color2" },
                new Color { ID=24, Name= "Color1" },
                    new Color { ID=25, Name= "Color2" }
            } .Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();


            ViewBag.MyUserName = contactsListItems;
            return View( );
        }

and  on page

@{
    ViewBag.Title = "About";
}
@Html.BeginForm(){ 

   @Html.DropDownList("MyUserName", null, "Select Country", htmlAttributes: new { @class = 
     "form-control", @required = "required" })
     <button>click me</button>

}

The key point is that these 3 name is same,"MyUserName"

Please have a check again, then it must work;

Bests,

Jolie


Thursday, March 22, 2018 5:51 AM ✅Answered

<g class="gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="8" data-gr-id="8">Hi</g> <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" id="5" data-gr-id="5">jamiie</g>,

Is there a better way to doing it than the way I was?

Sir, I have to say that this way is the easiest way in MVC

 List<SelectListItem> contactsListItems  = new List<Color> {
                new Color { ID=22, Name= "Color1" },
                new Color { ID=23, Name= "Color2" },
                new Color { ID=24, Name= "Color1" },
                    new Color { ID=25, Name= "Color2" }
            } .Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();


            ViewBag.MyUserName = new SelectList(contactsListItems , "Value", "Text");

2 and if from DB

List<SelectListItem> contactsListItems  = db.Colors.Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();

  ViewBag.MyUserName = new SelectList(contactsListItems , "Value", "Text");

Bests,

Jolie


Monday, March 12, 2018 4:41 PM

I want it so that when the submitted button is clicked the selected value is still selected. How do I go about this?

You could look at the code in the link, and you can lookup using Bing or Google how to use the SelectListItem with a dropdownlist. You can look at the controller and model logic on how the selected value in the dropdownlist stays on the selected value in the dropdownlist, even after the submit button is pressed and there is an error on the page. 

https://forums.asp.net/t/2137530.aspx?Select+Dropdown+list+from+one+DB+table+and+Save+Selected+vale+into+another+table+in+MVC+System+ArgumentNullException


Monday, March 12, 2018 6:12 PM

Is there a way to do it so that I don't reference the model directly in the view? My view is in razor format and every time I refer a field in the model I get "IEnumerable<Strategy> does not contain a definition for OSR and no extension method 'OSR' accepting a first argument of type 'IEnumerable<Strategy> could be found"


Monday, March 12, 2018 6:21 PM

You'll need to set the selected value for each Dropdown which can be done using the SelectList(IEnumerable, Object) constructor.

https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.selectlist(v=vs.118).aspx#M:System.Web.Mvc.SelectList.

Initializes a new instance of the SelectList class by using the specified items for the list and a selected value.

You might look into building a ViewModel that includes the selected value and SelectList rather than passing values in the ViewBag.  Or maybe pass the selected value through the ViewBag as well.

The following links explains how to handle dropdown lists in MVC.

/en-us/aspnet/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

https://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx


Tuesday, March 13, 2018 10:00 AM

<g class="gr_ gr_32 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="32" data-gr-id="32">Hi</g> <g class="gr_ gr_8 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" id="8" data-gr-id="8">jamiie</g>,

. For 3 of <g class="gr_ gr_44 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="44" data-gr-id="44">them </g><g class="gr_ gr_43 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" id="43" data-gr-id="43"><g class="gr_ gr_44 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace" id="44" data-gr-id="44">,</g>the</g> selected value sticks after I press submit. However for one of the <g class="gr_ gr_42 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="42" data-gr-id="42">drop down</g> lists bounces back to the default value.

Sir, please note this point and this is what you never show us, this is the key code which can pass the selected value;

ep.

Here is the full working code

        public ActionResult About(string MyUserName=null)// this is the key line code which pass the selected value of dropdownlist collection
        {
            List<SelectListItem> contactsListItems  = new List<Color> {
                new Color { ID=22, Name= "Color1" },
                new Color { ID=23, Name= "Color2" },
                new Color { ID=24, Name= "Color1" },
                    new Color { ID=25, Name= "Color2" }
            } .Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();


            ViewBag.MyUserName = new SelectList(contactsListItems , "Value", "Text");
            return View( );
        }

and  on page

@{
    ViewBag.Title = "About";
}
@Html.BeginForm(){ 

   @Html.DropDownList("MyUserName", null, "Select Country", htmlAttributes: new { @class = 
     "form-control", @required = "required" })
     <button>click me</button>

}

So, please check your parameters which in the method of the controller; and this is why your all code is same, but differently;

With regards, Angelina Jolie


Tuesday, March 13, 2018 1:29 PM

Hello,

Thank you for your response! It is the OSR dropdown that isn't sticking. I went back to check and they all getting passed in. Using breakpoints, I know the value is getting passed in when I hit the submit button but once I return the view and the page refreshes with the filtered results, the OSR dropdown gets reset to the "--Select--" value. 

public ActionResult Index(string group, string prin, string status, string osr, string groupnew, string stratvar, string fltstring, Strategy selg, FormCollection form)

Tuesday, March 13, 2018 4:29 PM

because you are using the dropdownlist instead of the dropdownlistfor, you set the selected option when you build the selectlist 

@Html.DropDownList("osr", new SelectList(ViewBag.OSRcmb, Model.OSR), "--Select--")

note: but doesn't appear you pass the model, so the above would probably fail.


Tuesday, March 13, 2018 4:43 PM

Yea I'm not passing in the model. Is there a way to do it without passing in a model?


Tuesday, March 13, 2018 4:57 PM

Yea I'm not passing in the model. Is there a way to do it without passing in a model?

As stated above, pass the selected value in the ViewBag if you do not wish to follow convention and create a strongly typed View.


Tuesday, March 13, 2018 5:10 PM

jamiie

Yea I'm not passing in the model. Is there a way to do it without passing in a model?

As stated above, pass the selected value in the ViewBag if you do not wish to follow convention and create a strongly typed View.

When I try passing it in into another ViewBag I come across an error:

View:

       @if (ViewBag.osrsel != null) { 
            <td>
             OSR
             @Html.DropDownList("osr", new SelectList(ViewBag.OSRcmb), ViewBag.osrsel)
            </td>
       }

HtmlHelper<IEnumerable<Strategy>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Controller: 

 else
                    {


                        //var selectedvalpr = form["prin"];

                        //var selectedvalosr = form["osr"];

                        //var selectedvalstatus = form["status"];

                        //var selectedvalosr = form["osr"];


                        var groups = from g in db.Strategies
                                     select g;
                        var prins = from pr in db.Strategies
                                    select pr;
                        var osrs = from o in db.Strategies
                                   select o;
                        var statuss = from s in db.Strategies
                                      select s;


                        ViewBag.Groupcmb = (from g in db.Strategies.Include(p) where g.Group != null
                                         select g.Group).Distinct();

                        ViewBag.Principalcmb = (from pr in db.Strategies.Include(p) where pr.Principal != null
                                             select pr.Principal).Distinct();

                        ViewBag.OSRcmb = (from o in db.Strategies.Include(p)
                        where o.OSR != null
                        select o.OSR).Distinct();


                        ViewBag.Statuscmb = (from s in db.Strategies.Include(p) where s.Status != null
                                          select s.Status).Distinct();


                        //ViewData["OSR"] = new SelectList(ViewBag.OSRcmb);
                        ViewBag.osrsel = osr;

                        //if all filters are null
                        if (group == null && stratvar == null && prin == null && osr == null && status == null)
                        {
                            return View(db.Strategies.ToList());
                        }

                        //returns same search filter for group if edit 
                        if (stratvar != null && group == null)
                        {

                            group = stratvar;
                            groups = groups.Where(g => g.Group.Contains(group));
                            //  return View(group.ToList());
                        };



                        if (prin != null && group != null && osr != null && status != null)
                        //if (group != null)
                        {

                            prins = prins.Where(gpr => gpr.Principal.Contains(prin) && gpr.Group.Contains(group) && gpr.OSR.Contains(osr) && gpr.Status.Contains(status));
                            stratvar = null;
                            return View(prins.ToList());
                        }


                        return View(strat);
                    }

I'm not too familiar with how to create a strongly type view.


Tuesday, March 13, 2018 5:31 PM

The syntax is incorrect.

@Html.DropDownList("osr", new SelectList(ViewBag.OSRcmb, ViewBag.osrsel), "--Select--")

SelectList Reference doc

https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.selectlist(v=vs.118).aspx#M:System.Web.Mvc.SelectList.

I'm not too familiar with how to create a strongly type view.

I think it is beneficial to learn strongly typed views in MVC because that is the convention as it's the "M" in MVC.   The problem with using ViewBag is you lose intellisense, the use of "for" HTML helpers, and the code can become complex and difficult to maintain.

The Learn link above has many excellent tutorials. 

https://www.asp.net/learn


Tuesday, March 13, 2018 5:45 PM

mgebhard

The syntax is incorrect.

@Html.DropDownList("osr", new SelectList(ViewBag.OSRcmb, ViewBag.osrsel), "--Select--")

SelectList Reference doc

https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.selectlist(v=vs.118).aspx#M:System.Web.Mvc.SelectList.

jamiie

I'm not too familiar with how to create a strongly type view.

I think it is beneficial to learn strongly typed views in MVC because that is the convention as it's the "M" in MVC.   The problem with using ViewBag is you lose intellisense, the use of "for" HTML helpers, and the code can become complex and difficult to maintain.

The Learn link above has many excellent tutorials. 

https://www.asp.net/learn

It's still not sticking with the correct syntax. If my index page starts with 

@model IEnumerable<WebApplication2.Models.Strategy>

@{
    ViewBag.Title = "Index";
}

<h4>Index</h4>

Does that mean it is already a strongly type view?


Monday, March 19, 2018 2:00 PM

Hi jamiie,

jamiie

<div>@model IEnumerable<WebApplication2.Models.Strategy></div> <div> </div> <div>@{</div> <div>    ViewBag.Title = "Index";</div> <div>}</div> <div> </div> <div><h4>Index</h4></div> <div>Does that mean it is already a strongly type view?

</div> <div>Yes, it is a strong type view now, but it is not the point why you can't get work with your updated selected dropdown list value; </div>

jamiie

Is there a way to do it without passing in a model?

Sir, in fact, i have answered the question in my post before.

ep.

Here is the full working code

        public ActionResult About(string MyUserName=null)// this is the key line code which pass the selected value of dropdownlist collection
        {
            List<SelectListItem> contactsListItems  = new List<Color> {
                new Color { ID=22, Name= "Color1" },
                new Color { ID=23, Name= "Color2" },
                new Color { ID=24, Name= "Color1" },
                    new Color { ID=25, Name= "Color2" }
            } .Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();


            ViewBag.MyUserName = contactsListItems;
            return View( );
        }

and  on page

@{
    ViewBag.Title = "About";
}
@Html.BeginForm(){ 

   @Html.DropDownList("MyUserName", null, "Select Country", htmlAttributes: new { @class = 
     "form-control", @required = "required" })
     <button>click me</button>

}

The key point is that these 3 name is same,"MyUserName"

Please have a check again, then it must work;

Bests,

Jolie

I went back to make sure the 3 parts matches and I run into this error. Just to clarify my problem isn't that the value isn't passing in when the submit button is clicked. The value is getting passed in. However once submit is clicked the OSR dropdownlist is getting reset whereas the others are staying. I want it so that all of the selected values stay selected once the submit button is clicked. 


The ViewData item that has the key 'OSRcmb' is of type 'System.Data.Entity.Infrastructure.DbQuery`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' but must be of type 'IEnumerable<SelectListItem>'.


Tuesday, March 20, 2018 10:12 AM

Hi jamiie,

ViewBag.MyUserName = contactsListItems;

Please change to 

ViewBag.MyUserName= new SelectList(contactsListItems , "Value", "Text");

and make sure that all code looks same as mine, then it must be work:)

Bests,

Jolie


Tuesday, March 20, 2018 12:35 PM

Hi jamiie,

jamiie

ViewBag.MyUserName = contactsListItems;

Please change to 

ViewBag.MyUserName= new SelectList(contactsListItems , "Value", "Text");

and make sure that all code looks same as mine, then it must be work:)

Bests,

Jolie

But I want my viewbag to list all the unique values from a table in my database. I do not want to manually add each value into a select list. Is there a better way to doing it than the way I was?


Thursday, March 22, 2018 2:43 PM

AngelinaJolie

Hi jamiie,

jamiie

Is there a better way to doing it than the way I was?

Sir, I have to say that this way is the easiest way in MVC

 List<SelectListItem> contactsListItems  = new List<Color> {
                new Color { ID=22, Name= "Color1" },
                new Color { ID=23, Name= "Color2" },
                new Color { ID=24, Name= "Color1" },
                    new Color { ID=25, Name= "Color2" }
            } .Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();


            ViewBag.MyUserName = new SelectList(contactsListItems , "Value", "Text");

2 and if from DB

List<SelectListItem> contactsListItems  = db.Colors.Select(d => new SelectListItem { Value = d.ID.ToString(), Text = d.Name   }).ToList();

  ViewBag.MyUserName = new SelectList(contactsListItems , "Value", "Text");

Bests,

Jolie

Thank you so much! This works!