locked
Can the ViewBag SelectListItem array become an argument in the dropdownlistfor? RRS feed

  • Question

  • User2142845853 posted

    Im trying to mix 2 databases with 1 Dropdownlistfor control.

    So far it works, but Im trying to modify the topmost entry in the list, nothing works.  Hopefully there is a way without having to iterate and construct it

    Goal:  top most entry in the dropdown list is set manually.  The rest are populated from a database with ajax call.  When the user clicks an item, the function is called to pass that value into the textbox on the main form, and it gets saved or shown.

    But the first entry in the dropdown list is the first item in that database.  No, It needs to be set manually.  Am trying to add to the control in some way like:

      @{
                                    List<SelectListItem> pmatch111 = new List<SelectListItem>();
    
                                    pmatch111.Add(new SelectListItem
                                    {
                                        Text = "Select a Name",
                                        Value = "1"
                                    });
                                    pmatch111.Add(
                                        ViewBag.NameCustdata
                                    );
                                }

    in the call, 

              @Html.DropDownList("pmatch111", null, new { @onchange = "CustTextBox(this)", style = "height:30px; width:245px; " })
    

    have tried DropDownlist and DDLFor.  first element should be manually set

    Friday, April 8, 2016 5:57 PM

Answers

  • User225117742 posted

    rogersbr

    thanks!  so that will set the first item.  that problem's solved but then what about inserting the listview from viewbag into the remaining items?  in my case it would only have one item at the top, but be filled from the viewbag instantiated

       ViewBag.Namemydata = new SelectList(db.InfoTables, "Id", "Namecust");
    

    In the controller try something like this.

    var myList = db.InfoTables.ToList();
    myList.Insert(0, new InfoTable(Id = 0, Namecust = "-- Select One --"));
    ViewBag.Namemydata = new SelectList(myList, "Id", "Namecust", 0);
    

    Create a list variable with data from db.InfoTables.
    Insert the "Select One" item to the beginning of the list
    Use the list variable to create the SelectList with the Id field for the value, Custname for the text and the 0 is the selected value which should set it to "-- Select One--"

    If you already have a record Id with 0, then change the "-- Select One --" to -1

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 16, 2016 3:22 PM

All replies

  • User-1355486065 posted

    But the first entry in the dropdown list is the first item in that database.  No, It needs to be set manually.  Am trying to add to the control in some way like:

    What you mean by this?

    Saturday, April 9, 2016 4:18 AM
  • User1930269528 posted

    You have to set Selected property of SelectListItem to true, if you want to set it Selected :

    pmatch111.Add(new SelectListItem
                                    {
                                        Text = "Select a Name",
                                        Value = "1",
                                        Selected = true
                                    });

    Saturday, April 9, 2016 11:43 AM
  • User2142845853 posted

    You have to set Selected property of SelectListItem to true, if you want to set it Selected :

    pmatch111.Add(new SelectListItem
                                    {
                                        Text = "Select a Name",
                                        Value = "1",
                                        Selected = true
                                    });

    Thanks.  That is the right way for this part.  But it was not erroring out here, it will not work at all as Im trying to do it because it will not take the ViewBag.item 

    So if I try to put the selectlistitem first as you wrote, then how does the ViewBag.item which is fed as an array of list items, get added in there also?  Right now if its using DropDownList(    then I can put the ViewBag.item name in quotes " " and it somehow decodes this as coming from ViewBag and accepts it, and the dropdown works.  I then add an OnChange() function and extract the value of what was clicked and manually send this into an @Html.HiddenFor( myothervariable ), which used to be EditorFor( myothervariable ).  

    The way its setup?  I have to maintain what will be displayed at the top of the dropdown list by putting it into the database at the 1st ID, but this seems wrong. 

    The goal is to be able to force some text in there for the first selectlistitem, exactly as you mentioned, but what about the rest of the contents? nothing I do works, either it wont compile or crashes at runtime.  It also needs to have the ability to display whats in the @Html.HiddenFor (myothervariable) as the top item in the list, if its not null.

    So if there is nothing in there?  show the "select a name" text.  If its stored? display what is stored.  but how?  can you force it by an index reference?  dropdownlist[0] = "john smith" ?

    Saturday, April 9, 2016 11:48 PM
  • User2142845853 posted

    But the first entry in the dropdown list is the first item in that database.  No, It needs to be set manually.  Am trying to add to the control in some way like:

    What you mean by this?

    Ok, well I can make this work with @Html.DropdownList(..)  and add in the ViewBag.items reference, and it fills it with the items I return in the controller, works fine.

    It does NOT work if I try to add in the ViewBag.items in an @Html.DropDownListFor(..)  I can only use manual items declared and put into the list.  There is a variable, a string that must be stored, hence the dropdownlistFor.  it was @Html.EditorFor() but is being modified to accept only what comes from a database of pre defined names

    I wish the drodownlistFor would work, if I could just get the contents to be filled from my working ViewBag.items as works with the DropDownList(), they seem to be from different worlds altogether.  so the behavior should be:  if the variable behind the dropdown is null?  put the string message:  "--Select a Name--".  but if the variable is not null, then display that string value there at the top.  AND, put the contents of the names table in there, its coming from the ViewBag.items

    Whatever the user selects from that list?  goes to the top, as any dropdown list should do.  click Save on that Edit or Create.cshtml page?  and it will update the database and write that value into the variable behind.  when going back to the page in Edit or Details, the value is shown that was stored.  

    it will not compile or it crashes at runtime.  trying to find how to make this work

    Sunday, April 10, 2016 12:16 AM
  • User225117742 posted

    After creating your list try using List.Insert() to insert a new select list item at position 0 to make it first in the list.

    @{ 
        List<SelectListItem> MyItems = new List<SelectListItem>();
    
        MyItems.Add(new SelectListItem() { Text = "Item 1", Value = "1" });
        MyItems.Add(new SelectListItem() { Text = "Item 2", Value = "2" });
        MyItems.Add(new SelectListItem() { Text = "Item 3", Value = "3" });
        MyItems.Add(new SelectListItem() { Text = "Item 4", Value = "4" });
    
        // Use Insert to place new SelectListItem first in the list
        MyItems.Insert(0, new SelectListItem() { Text = "First Item", Value = "0" });
    }
    

    Sunday, April 10, 2016 3:23 PM
  • User2142845853 posted

    After creating your list try using List.Insert() to insert a new select list item at position 0 to make it first in the list.

    @{ 
        List<SelectListItem> MyItems = new List<SelectListItem>();
    
        MyItems.Add(new SelectListItem() { Text = "Item 1", Value = "1" });
        MyItems.Add(new SelectListItem() { Text = "Item 2", Value = "2" });
        MyItems.Add(new SelectListItem() { Text = "Item 3", Value = "3" });
        MyItems.Add(new SelectListItem() { Text = "Item 4", Value = "4" });
    
        // Use Insert to place new SelectListItem first in the list
        MyItems.Insert(0, new SelectListItem() { Text = "First Item", Value = "0" });
    }
    

    thanks!  so that will set the first item.  that problem's solved but then what about inserting the listview from viewbag into the remaining items?  in my case it would only have one item at the top, but be filled from the viewbag instantiated

       ViewBag.Namemydata = new SelectList(db.InfoTables, "Id", "Namecust");
    

    Sunday, April 10, 2016 3:40 PM
  • User2142845853 posted

    using the viewbag "view model" data to fill the dropdownlistFor, what it does now is stores the VALUE not the TEXT...  first item in the list? my model.varname = 0  pick the next item now its 1.  

    tried using jquery to force the name value anyway?  has no effect.  

    Monday, April 11, 2016 2:54 AM
  • User2142845853 posted

    Update:

    The Html.DropDownListFor( .... )   I can make it hold and display the values in the list, but in the database? it stores an Int value for the number in the list.

    --Edit.cshtml code:	
    
    
                              @{
                                    List<SelectListItem> pmatch111 = new List<SelectListItem>();
                                    pmatch111.Add(new SelectListItem
                                    {
                                        Text = "Select Outside Customer",
                                        Value = "Yes"
                                    });
                                    foreach (var item in ViewBag.NameCustData)
                                    {
                                        pmatch111.Add(new SelectListItem
                                        {
                                            Text = item.Text,
                                            Value = item.Value
                                        });
                                    }
    
                                }
    							
    						
    		<div class="form-group">
                        @Html.LabelFor(model => model.NameCust1, new { @class = "control-label col-md-3" })
                        <div class="col-md-8">
                            @Html.DropDownListFor(model => model.NameCust1, pmatch111, null, new { style = "height:30px; width:245px; " })
                            @Html.ValidationMessageFor(model => model.NameCust1)
                        </div>
                    </div>
    				
    	--controller code: 
    	  ViewBag.NameCustdata = new SelectList(db.InfoTables,"Id", "NameCust1");

    Now the @Html.DropDownListFor(...model.NameCust1  gets stored in the main database table.  but db.InfoTables is a different database table  what happens?  is the model.NameCust1 only gets a 1, 2, 3, etc based on the index of the selected item in the SelectList, that is brought in from db.InfoTables.  This is wrong.  it SHOULD be storing the name selected in the main table, not a number! 

    Monday, April 11, 2016 8:05 PM
  • User225117742 posted

    rogersbr

    thanks!  so that will set the first item.  that problem's solved but then what about inserting the listview from viewbag into the remaining items?  in my case it would only have one item at the top, but be filled from the viewbag instantiated

       ViewBag.Namemydata = new SelectList(db.InfoTables, "Id", "Namecust");
    

    In the controller try something like this.

    var myList = db.InfoTables.ToList();
    myList.Insert(0, new InfoTable(Id = 0, Namecust = "-- Select One --"));
    ViewBag.Namemydata = new SelectList(myList, "Id", "Namecust", 0);
    

    Create a list variable with data from db.InfoTables.
    Insert the "Select One" item to the beginning of the list
    Use the list variable to create the SelectList with the Id field for the value, Custname for the text and the 0 is the selected value which should set it to "-- Select One--"

    If you already have a record Id with 0, then change the "-- Select One --" to -1

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 16, 2016 3:22 PM