locked
Dropdownlist in the mvc edit view VB.NET RRS feed

  • Question

  • User2130491911 posted

    So the situation. 

    I have a database that has data inside it. I have used the wizard to create the edit view so that I can update the database.

    The problem I am having now is that when I click edit my drop down list shows the first Item in the list and not the value that was on the edit form.

    Is there a way to get the database value to be the value that is displayed in the dropdownlist ?

    The database does not store the ID field from the drop downlist. It stores the text descriptions  (That was a requirement that can't be changed sadly)

    For sample of the Dropdownlist

    • ID:1  VALUE:RED
    • ID:2 VALUE:YELLOW

    The value that gets stored is YELLOW or RED and not the 1 or 2

    The Dropdownlist gets made and passed to a viewbag and then on to the form view

    source codes: Edit View

    @ModelType BFR_LOCAL_DB.CODE_OPINIONS_TBL
    @Code
        ViewData("Title") = "CO-EDITOR"
    End Code
    
    
    <h2>EDIT / UPDATE / MODIFY </h2>
    
    @Using (Html.BeginForm())
        @Html.AntiForgeryToken()
        
        @<div class="form-horizontal">
        <h4>CODE OPINIONS EDIT</h4>
        <hr />
        @Html.ValidationSummary(True, "", New With {.class = "text-danger"})
        @Html.HiddenFor(Function(model) model.ID)
    
        @*<div class="form-group">
                @Html.LabelFor(Function(model) model.Code_Reference, htmlAttributes:= New With { .class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Code_Reference, New With { .htmlAttributes = New With { .class = "form-control" } })
                    @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With { .class = "text-danger" })
                </div>
            </div>*@
    
        <div class="form-group">
            @Html.LabelFor(Function(model) model.Code_Reference, htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})
                @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With {.Class = "text-danger"})
            </div>
        </div>
        End Using
    
        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
    
        @Section Scripts
            @Scripts.Render("~/bundles/jqueryval")
        End Section
    

    The Dropdownlist in the edit view

                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})

    The Two Edit options in the controller

            ' GET: CO/Edit/5
            Function Edit(ByVal id As Integer?) As ActionResult
    
    
                If IsNothing(id) Then
                    Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
                End If
    
                Dim cODE_OPINIONS_TBL As CODE_OPINIONS_TBL = db.CODE_OPINIONS_TBL.Find(id)
    
                If IsNothing(cODE_OPINIONS_TBL) Then
                    Return HttpNotFound()
                End If
    
                'Populate List of Values 
                'GET_SELECTED_CODE_REF_List(cODE_OPINIONS_TBL.Code_Reference.ToString())
    
                ViewBag.RefCodesList = GET_CODE_REF_List()
    
                Return View(cODE_OPINIONS_TBL)
            End Function
            ' POST: CO/Edit/5
            'To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            'more details see https://go.microsoft.com/fwlink/?LinkId=317598.
            <HttpPost()>
                                <ValidateAntiForgeryToken()>
            Function Edit(<Bind(Include:="ID,Code_Reference,Chapter,Section,Response_Date,Year,Status,Author,From,Locality,Description,Comments,Attachments")> ByVal cODE_OPINIONS_TBL As CODE_OPINIONS_TBL) As ActionResult
                If ModelState.IsValid Then
                    db.Entry(cODE_OPINIONS_TBL).State = EntityState.Modified
                    db.SaveChanges()
                    Return RedirectToAction("Index")
                End If
                Return View(cODE_OPINIONS_TBL)
            End Function

    The is the stuff that makes the list but I am not sure how I would tell it to select the values from the database so that it displays that as selected

                Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_DESCRIPTION.ToString()}).ToList()

    I tried something like this: Thinking I could end the value to the function that makes the list

    Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_DESCRIPTION.ToString(), .Selected = c.CODE_DESCRIPTION = SelectID}).ToList()

    The Attempted to send the selected value to the list maker so that the viewbag can send it back to the edit form

            'GET SELECTED CLE-LIST-ITEM
            Function GET_SELECTED_CODE_REF_List(SelectID As String)
    
                Dim selected As String = (From c In db.CODE_REF_LOV_TBL Where c.CODE_DESCRIPTION = SelectID Select c.CODE_REF_CAT).First()
    
                Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_DESCRIPTION.ToString()}).ToList()
                ' Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_DESCRIPTION.ToString(), .Selected = c.CODE_DESCRIPTION = SelectID}).ToList()
    
    
                'See: https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/
    
    
                Return REF_CODES_LIST
    
            End Function

    I was a bit shocked that the dropdowns did not automatically display the value that was on the source form. Any insight would be great 

    Also would it just be easier to just keep the edit for field and just add the dropdownlist to the form as an extra field that is used to update it? 

    Wednesday, May 19, 2021 5:42 PM

Answers

  • User475983607 posted

    I illustrated how to select an option in your other recent thread.  Also, it confusing why you keep going back to the manually building a List<SelectListItem> when the SelectList has the same capability.  SelectList is less code and less room for you to mess it up. 

    The SelectList overload shown below creates an internal List<SelectListItem> and sets the selected option to SelectValueID.  Please note the Function returns a defined type.  You keep forgetting the return type in your recent threads.

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return New SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    Now that the SelectList is built, all you have to do is pass the SelectList via the ViewBag which I think we've covered to death at this point.

    ViewBag.CODE_REF_LOV_TBL_ID = GET_SELECTED_CODE_REF_VALUE(YourIdVariableGoesHere)

    The last step is writing the View markup.  The syntax depends, somewhat, on the View design.

    If you have not defined a @ModelType then use the DropDownList() helper.

    @Html.DropDownList("CODE_REF_LOV_TBL_ID ")

    If you defined a @ModelType and you want to use a parameter you defined in the @ModelType, then use the DropDownListFor() helper.  My @ModelType has a property named CODE_REF_LOV_TBL_ID.  I'm not sure what property name you're currently are using. 

    <div>
        @Html.DropDownListFor(Function(m) m.CODE_REF_LOV_TBL_ID, CType(ViewBag.CourseID, SelectList))
    </div>

    Unfortunately, there's no way to know if db.CODE_REF_LOV_TBL returns values, if the result set contains "CODE_REF_ID" and "CODE_DESCRIPTION" columns, or if there are any other coding issues.   I recommend using the Visual Studio debugger if your results are unexpected.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 26, 2021 6:00 PM

All replies

  • User-474980206 posted

    you first need to understand how the select works in the browser 

    html: no option selected, browser will auto select the first:

      <select name="Foo"><option value="1"><option value="2"></select>

    html: second option selected

      <select name="Foo"><option value="1"><option value="2" selected></select>

    the html helper just renders a select. the simplest version is the name and the list (only know c#)

       @Html.DropDownList("Foo", new List<SelectListItem> 
       {
            new SelectListItem {Value="1", Text="1" },
            new SelectListItem {Value= "2", Text="2"}
       })

    if you want the second option selected its:

       @Html.DropDownList("Foo", new List<SelectListItem> 
       {
            new SelectListItem {Value="1", Text="1" },
            new SelectListItem {Value= "2", Text="2", Selected=true}
       })
    

    if you want to render the list with the option selected that matches the post back value its (assume post back model named model and has matching property:

    in controller:
    
    ViewBag.FooOptions = new List<SelectListItem> 
    { 
        new SelectListItem {Value="1", Text="1" }, 
        new SelectListItem {Value= "2", Text="2"} 
    }).Select(r => new SelectListItem 
    {
        Value = r.Value,
        Text = r.Text,
        Selected = r.Value == model.foo
    }).ToList();
     
    in view
    
      @Html.DropDownList("Foo", (IEnumerable<SelectListItem>)ViewBag.FooOptions)
     

    the hard coded list could easily be replaced with a database call:

    ViewBag.FooOptions = db.MyTable.Select(r => new List<SelectListItem> 
    { 
         Value = r.Col1,
         Text = r.Col2
         Selected = r.Col1 == model.Foo 
    }).ToList();  

    the other option is use the more full featured DropDownListFor, which uses binding to set the option value for you. so if Model.Foo == "2", the second option will be rendered as selected (the model must be passed to the view):

    @Html.DropDownListFor(m => m.Foo, new List<SelectListItem> 
    { 
        new SelectListItem {Value="1", Text="1"}, 
        new SelectListItem {Value= "2", Text="2"}
    })

    note: I almost aways use binding and the ...For version of the tag helpers. 

    Wednesday, May 19, 2021 6:42 PM
  • User2130491911 posted

    Hi Bruce thanks.

    But this is not quite what I am looking for. Yes I figured that they the system would have to be told what was selected by the user but in our situation the mvc form has values that it gets from the database. So from the index view the user clicks edit and when the edit view comes up there is already a value loaded to the field.

    In the create view we allow the user to use a dropdownlist to add a value to that field.

    So for example the users has the following options from database.

    • -- SELECT COLOUR OPTIONS --  (Represents a place holder)
    • RED
    • ORANGE
    • BLACK
    • BROWN

    In the index view the user picks a line items:

    USER ID USER NAME FIRST  USER NAME LAST TROUSER COLOUR EDIT | DETAILS | DELETE
    1 GUY TESTER RED EDIT | DETAILS | DELETE
    2 GAL TESTS BLACK EDIT | DETAILS | DELETE
    3 NU TESTINGS ORANGE EDIT | DETAILS | DELETE
    4 OLDS TESTED BLACK EDIT | DETAILS | DELETE

    When the user clicks EDIT for Record #1 The mvc wizard made a edit form that allows the user to edit the record.  

    ID 2
    USER NAME FIRST GUY
    USER NAME LAST TESTER
    TROUSER COLOUR RED

    We have changed the form above to have a dropdown field  So now it renders like the following 

    ID 2
    USER NAME FIRST GUY
    USER NAME LAST TESTER
    TROUSER COLOUR [ -- SELECT COLOUR OPTIONS --  V]                                        

    What we would like it to do is the following 

    ID 2
    USER NAME FIRST GUY
    USER NAME LAST TESTER
    TROUSER COLOUR [ RED V]                                        

    And if the user decides to edit that field they can click that dropdown and it will show the rest of the list. The one issue we have with the data is that the COLOUR LIST does not store the ID of the List of values into the database it stores the actual text value to the table.

    So looking at you example. I can red both C# and VB.net... but looking at you example which differs from my example as I make my list as a function inside of the controller an my list is using something called the selectlistitem can I passed the value into that list make and have it get selected?

    Not even sure if I am asking the question correctly ?

    In Past application I did something creative where I use the java scripting where I locked the fields to prevent them from changes sections of the ofrm and if they wanted to change a value that was controlled by a dropdown I hid the Editfor field and replaced with the drop down field where they could make a new selection since I did not think it was possible to do this when you have a database as the backend. That may be still the case but if it is not the case it would be nice to see how it can be done so that some much extra source code would not have to be written for something that is so simple to do in webforms. Thanks

    Wednesday, May 19, 2021 8:16 PM
  • User-474980206 posted

    So looking at you example. I can red both C# and VB.net... but looking at you example which differs from my example as I make my list as a function inside of the controller an my list is using something called the selectlistitem can I passed the value into that list make and have it get selected?

    what part is not clear. every SelectListItem has a Selected property you set. (<select multiple> allow more than 1 selection). I gave a sample of setting the selected option in the controller, even via a database call for the list. Do you not know Linq? Its a simple mapping query.

    what is so hard to understand? a html option has 3 properties, value, text and selected. the SelectListItem has 3 properties, Value, Text and Selected, that exactly map to the option values. only the case is different due to .net naming standards.

    Wednesday, May 19, 2021 9:05 PM
  • User2130491911 posted

    I think what is unclear is that you example show this with two selections that  get picked but the programmer. 

    I have a list of options and data store in database.. I will not know what the user has selected.

    I think this concept may be too advance for my understanding. I have the dropdown list working. 

    I will just have to do something creative with the drop down list when the form is in edit mode. as stated. I can do what I did before and hide the drop list and force the user to edit that field independently or use some sort of java scripting or something.

    Thanks bruce!

    I wonder why microsoft made this sooooooooooo difficult lol! I guess they have their reasons. THey really should rethink this as dorpdown list are common and they have to know that people will need to use the edit option at some point and may want to use a drop down list to change a value. 

    Its beyond crazy!! LOL

    Thursday, May 20, 2021 8:06 PM
  • User475983607 posted

    AppDev01

    I have a list of options and data store in database.. I will not know what the user has selected.

    I think this concept may be too advance for my understanding. I have the dropdown list working. 

    I will just have to do something creative with the drop down list when the form is in edit mode. as stated. I can do what I did before and hide the drop list and force the user to edit that field independently or use some sort of java scripting or something.

    I shared an example in your other recent ramblings that specifically shows how to programmatically make a selection.  It is beyond easy. You just pass the item to want selected in an overload.  

    Thursday, May 20, 2021 9:05 PM
  • User2130491911 posted

    Yeah I think our issue is that the id is not stored so.  I think the example you shared was something with manual list and and used select list. My list used something called selectlistitem so I doubt it all works the same as there is no clear information that I found on the microsoft sites that explains how the dropdownlist thing works all that well.

    I may have to keep looking and please remember easy to you may be a night mare to others. 

    Also I think if it were easy there would not be millions of questions about them on the internets.

     

    Monday, May 24, 2021 1:48 PM
  • User475983607 posted

    I may have to keep looking and please remember easy to you may be a night mare to others. 

    Also I think if it were easy there would not be millions of questions about them on the internets.

    This is another one of your many unfounded assumptions.   There are many question because there have been many beginning level developers throughout the years.   

    You're situation is atypical.  You've ask the same select list question every few months over the last several years.   Most developers figure out the programming construct in a few minutes to an hour or two.  It's been 5 years...  that's unique.

    Monday, May 24, 2021 2:29 PM
  • User2130491911 posted

    Yes its a very difficult concept and I am not a programmer so that may have something to do with it. 

    One day maybe microsoft will make some usable guides that will be helpful to people that don;t leave and breath this stuff daily.

    For those in the same boat I found this web https://dotnettutorials.net/lesson/dropdownlist-html-helper-mvc/

    It may be helpful although it does not sure the user how to do edits 

    Tuesday, May 25, 2021 3:39 PM
  • User2130491911 posted

    bruce (sqlwork.com)

    AppDev01

    So looking at you example. I can red both C# and VB.net... but looking at you example which differs from my example as I make my list as a function inside of the controller an my list is using something called the selectlistitem can I passed the value into that list make and have it get selected?

    what part is not clear. every SelectListItem has a Selected property you set. (<select multiple> allow more than 1 selection). I gave a sample of setting the selected option in the controller, even via a database call for the list. Do you not know Linq? Its a simple mapping query.

    what is so hard to understand? a html option has 3 properties, value, text and selected. the SelectListItem has 3 properties, Value, Text and Selected, that exactly map to the option values. only the case is different due to .net naming standards.

    Hi Bruce can you be more clear on your meaning here? The Example  has the link information?? I may have missed this. The only example I have seen was a hard coded on I think and I did not see anything related to being in edit mode ?>

    IF you are referencing  the example above that appears to me manual? I need the value to come from the database. So when the user clicks edit that value that showed up on the details page in the editfor field now gets displayed in the dropdownlsit 3 in the edit view.

    Tuesday, May 25, 2021 3:50 PM
  • User475983607 posted

    AppDev01

    Yes its a very difficult concept and I am not a programmer so that may have something to do with it. 

    One day maybe microsoft will make some usable guides that will be helpful to people that don;t leave and breath this stuff daily.

    You don't consider yourself a web developer but you are performing web development tasks.  We all have the same tools and reference documentation.  You will not find a special guide that solves your specific problems or misunderstandings.  The idea is using the development tools to create a custom solution.    You have to take the time to understand the tools.

    AppDev01

    It may be helpful although it does not sure the user how to do edits 

    What is an edit in your world?   Get the value of the user's selection in an MVC action and update a record?  Populating an HTML from in an MVC View that represents a record?  Keep in mind, these type of tasks are covered in every beginning level MVC tutorial and I provided several examples.

    Tuesday, May 25, 2021 6:33 PM
  • User2130491911 posted

    mgebhard

    AppDev01

    Yes its a very difficult concept and I am not a programmer so that may have something to do with it. 

    One day maybe microsoft will make some usable guides that will be helpful to people that don;t leave and breath this stuff daily.

    You don't consider yourself a web developer but you are performing web development tasks.  We all have the same tools and reference documentation.  You will not find a special guide that solves your specific problems or misunderstandings.  The idea is using the development tools to create a custom solution.    You have to take the time to understand the tools.

    AppDev01

    It may be helpful although it does not sure the user how to do edits 

    What is an edit in your world?   Get the value of the user's selection in an MVC action and update a record?  Populating an HTML from in an MVC View that represents a record?  Keep in mind, these type of tasks are covered in every beginning level MVC tutorial and I provided several examples.

    Most of you points are true, but let us not put all the burden on the programmers. It is understood that the solution will have to be made by the user with the problem. But the documentation is horrible. It just is. No one can tell me any different as I have seen this and I have plugged through this nonsene for many years and yes you learn things to get the task done but a programmer I am not. LOL I would never submit myself to this pain on a daily basis. 

    What does edit mean in my world. Well In the mvc form wizard world edit means that the user can click on a line item from index page / screen and edit the details of that entry.

    THis is what the mvc says he wants to do, that i what he says he wants to do so I do it. But the wizard lives in a world where drop downs don't exist only the edit for elements.

    So when you add the dropdown list the wizard has no clue how to edit them.

    For what ever reason when you click edit you need to do the things over again that you did in the create screen, like resend the list and all this extra work. to get that list back on screen for edit but it comes back over as a list that seems to default to the top item of the list even when you have a different item set as the selected i..

    When it renders to the screen the value is not selected even it it shows that it is as you step through it . It shows in the watch, it show in the viewbag but when it renders the edit screen at least in my case it show True by selected but when it on the edit screen the list is just a list, that defaults to the first value as if I was on the create screen. It's beyond frustrating to work with in this stuff

    So the stuff that works.

    The Drop down

    The Selected Item True

    What is not working showing the selected value as selected in drop down list.

    If I replace the dropdownlistfor with The EditorFor. The proper value the proper value shows up.

    It beggers belief! But I am sure it is user error. 

    Here is all the related source codes

    The Edit View

        <div class="form-group">
            @Html.LabelFor(Function(model) model.Code_Reference, htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @*@Html.EditorFor(Function(model) model.Code_Reference, New With {.htmlAttributes = New With {.class = "form-control"}})*@
                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})
                @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With {.Class = "text-danger"})
            </div>
        </div>
    

    The Edit Controller

        <div class="form-group">
            @Html.LabelFor(Function(model) model.Code_Reference, htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @*@Html.EditorFor(Function(model) model.Code_Reference, New With {.htmlAttributes = New With {.class = "form-control"}})*@
                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})
                @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With {.Class = "text-danger"})
            </div>
        </div>
    

    The Controller Function used to select the selected ITEM

            'GET SELECTED CLE-LIST-ITEM
            Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String)
    
                'Get Value To Set Dropdown ID since stabase stores Description and not ID
                Dim SelectedID As Int16 = (From c In db.CODE_REF_LOV_TBL Where c.CODE_DESCRIPTION = SelectValueID Select c.CODE_REF_REC_ID).First()
    
                Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_REF_ID, .Selected = c.CODE_REF_REC_ID = SelectedID}).ToList()
    
                'See: https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/
    
    
                Return REF_CODES_LIST
    
            End Function

    What's binders is that if I step throught the source code I see my value selected as true.

    Is there a special drop down list for the edit screen I need to use maybe??

    This is what the view bag shows 

    -		REF_CODES_LIST	Count = 10	System.Collections.Generic.List(Of System.Web.Mvc.SelectListItem)
    +		(0)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(1)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(2)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(3)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(4)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(5)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(6)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(7)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    +		(8)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    -		(9)	{System.Web.Mvc.SelectListItem}	System.Web.Mvc.SelectListItem
    		Disabled	False	Boolean
    		[Group]	Nothing	System.Web.Mvc.SelectListGroup
    		Selected	True	Boolean
    		[Text]	"808 TEST"	String
    		Value	"TEST"	String
    +		Raw View		
    

    As shown here the source code is doing what it has been asked to do. The list gets made and the selected item in this case I tem 9 but for some reason that value will not render on the Edit view page after edit is selected 

    Tuesday, May 25, 2021 8:04 PM
  • User2130491911 posted

    Well I tried to post the page render it shows nicely at first but then when saved it turns into what you see but you can see the list of values works 

    <script src="/Scripts/modernizr-2.8.3.js"></script> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> </button> Application name</div> <div class="navbar-collapse collapse">

    </div> </div> </div> <div class="container body-content">

    EDIT / UPDATE / MODIFY

    <form action="/CO/Edit/1909" method="post"><input name="__RequestVerificationToken" type="hidden" value="QEqae6k8cIkBGcXqft_MwSDUNZgDxfOLy5eGuqS66w0DqwIc1Xs12Hbnx3bt16xXf7G_Gik-lBuqNvDprTqX-9khKj3z3yZyjjXUVIpxo4Y1" /> <div class="form-horizontal">

    CODE OPINIONS EDIT


    <input data-val="true" data-val-number="The field ID must be a number." data-val-required="The ID field is required." id="ID" name="ID" type="hidden" value="1909" /> <div class="form-group"><label class="control-label col-md-2" for="Code_Reference">Code_Reference</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Code_Reference" name="Code_Reference" type="text" value="808 TEST" />

    <select class="form-control" id="Code_Reference" name="Code_Reference"> <option value="VAVCC">xx</option> <option value="VAEBC">xxxxxx</option> <option value="VAMC">xxxxx</option> <option value="VADR">xxxxxx</option> <option value="VACS">xxxxx</option> <option value="VAIBSR">xxxx</option> <option value="VASFPC">xxxxx</option> <option value="VAMHLTRF">xxxxxxxxxx</option> <option value="VAMHSR">xxxxxxx</option> <option value="TEST">808 TEST</option> </select>

    </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Chapter">Chapter</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Chapter" name="Chapter" type="text" value="Testing" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Section">Section</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Section" name="Section" type="text" value="Test" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Response_Date">Response_Date</label> <div class="col-md-10"><input class="form-control text-box single-line" data-val="true" data-val-date="The field Response_Date must be a date." id="Response_Date" name="Response_Date" type="datetime" value="5/25/2021 12:00:00 AM" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Year">Year</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Year" name="Year" type="text" value="2021" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Status">Status</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Status" name="Status" type="text" value="Good" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Author">Author</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Author" name="Author" type="text" value="Testing Guy" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="From">From</label> <div class="col-md-10"><input class="form-control text-box single-line" id="From" name="From" type="text" value="xmond " /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Locality">Locality</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Locality" name="Locality" type="text" value="xd City" /> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Description">Description</label> <div class="col-md-10" style="height: 120px;"><textarea cols="50" id="Description" name="Description" rows="6">Testing</textarea> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Comments">Comments</label> <div class="col-md-10" style="height: 120px;"><textarea cols="50" id="Comments" name="Comments" rows="6">Testing to test thing </textarea> </div> </div> <div class="form-group"><label class="control-label col-md-2" for="Attachments">Attachments</label> <div class="col-md-10"><input class="form-control text-box single-line" id="Attachments" name="Attachments" type="text" value="" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-default" /></div> </div> </div> </form> <div>Back to List</div>


    © 2021 - My ASP.NET Application

    </div> <script src="/bundles/jquery"></script> <script src="/bundles/bootstrap"></script> <script src="/bundles/jqueryval"></script>

    Tuesday, May 25, 2021 9:15 PM
  • User2130491911 posted

    bruce (sqlwork.com)

    you first need to understand how the select works in the browser 

    html: no option selected, browser will auto select the first:

      <select name="Foo"><option value="1"><option value="2"></select>

    html: second option selected

      <select name="Foo"><option value="1"><option value="2" selected></select>

    the html helper just renders a select. the simplest version is the name and the list (only know c#)

       @Html.DropDownList("Foo", new List<SelectListItem> 
       {
            new SelectListItem {Value="1", Text="1" },
            new SelectListItem {Value= "2", Text="2"}
       })

    if you want the second option selected its:

       @Html.DropDownList("Foo", new List<SelectListItem> 
       {
            new SelectListItem {Value="1", Text="1" },
            new SelectListItem {Value= "2", Text="2", Selected=true}
       })

    if you want to render the list with the option selected that matches the post back value its (assume post back model named model and has matching property:

    in controller:
    
    ViewBag.FooOptions = new List<SelectListItem> 
    { 
        new SelectListItem {Value="1", Text="1" }, 
        new SelectListItem {Value= "2", Text="2"} 
    }).Select(r => new SelectListItem 
    {
        Value = r.Value,
        Text = r.Text,
        Selected = r.Value == model.foo
    }).ToList();
     
    in view
    
      @Html.DropDownList("Foo", (IEnumerable<SelectListItem>)ViewBag.FooOptions)
     

    the hard coded list could easily be replaced with a database call:

    ViewBag.FooOptions = db.MyTable.Select(r => new List<SelectListItem> 
    { 
         Value = r.Col1,
         Text = r.Col2
         Selected = r.Col1 == model.Foo 
    }).ToList();  

    the other option is use the more full featured DropDownListFor, which uses binding to set the option value for you. so if Model.Foo == "2", the second option will be rendered as selected (the model must be passed to the view):

    @Html.DropDownListFor(m => m.Foo, new List<SelectListItem> 
    { 
        new SelectListItem {Value="1", Text="1"}, 
        new SelectListItem {Value= "2", Text="2"}
    })

    note: I almost aways use binding and the ...For version of the tag helpers. 

    I there, my question is what is this .foo thing you are using? Is that what I am missing? Is this something I need to download? To get the edit feature work?

    I my example above the thing that seems different was that a user told me to convert the list using that ctype option, should I be using this foo option?

    I am not sure why I was told to convert it but that does allow me to display a list of values but and store the selection into the database but for some reason I can't edit and have that selected value displayed when in edit mode.

    As I stated before searching online shows this seems to be common issue with the mvc but there does not seem to be a clear solution. Does this require the java script? 

    THis is my select list options I don't have the foo function in there.. do I need that ?

            'GET SELECTED CLE-LIST-ITEM
            Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String)
    
                'Get Value To Set Dropdown ID since stabase stores Description and not ID
                Dim SelectedID As Int16 = (From c In db.CODE_REF_LOV_TBL Where c.CODE_DESCRIPTION = SelectValueID Select c.CODE_REF_REC_ID).First()
    
                Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_REF_ID, .Selected = c.CODE_REF_REC_ID = SelectedID}).ToList()
    
                'See: https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/
    
    
                Return REF_CODES_LIST
    
            End Function

    I can't really tell in what part of your example where you make you list but mine is in a function  outside of the edit option

    In the edit option it gets called :

            ' GET: CO/Edit/5
            Function Edit(ByVal id As Integer?) As ActionResult
    
    
                If IsNothing(id) Then
                    Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
                End If
    
                Dim cODE_OPINIONS_TBL As CODE_OPINIONS_TBL = db.CODE_OPINIONS_TBL.Find(id)
    
                If IsNothing(cODE_OPINIONS_TBL) Then
                    Return HttpNotFound()
                End If
    
                'Populate List of Values 
                 ViewBag.RefCodesList =GET_SELECTED_CODE_REF_VALUE(cODE_OPINIONS_TBL.Code_Reference.ToString())
    
    
    
                Return View(cODE_OPINIONS_TBL)
            End Function

    So the list gets pushed into the viewbag 

     and the view bad is displayed this way in the edits form. By all accounts this should work yes>?

        <div class="form-group">
            @Html.LabelFor(Function(model) model.Code_Reference, htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.EditorFor(Function(model) model.Code_Reference, New With {.htmlAttributes = New With {.class = "form-control"}})
                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})
                @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With {.Class = "text-danger"})
            </div>
        </div>

    Its so odd it says its selected and the value shows in the editfor field just not the down list even thought it shows in the watch that selected is true. 

    Hopefully this explains what is going on better than before. Thanks

    Should I remove the ctype from the drop down?

    Also what is throwing about your example is that your list is hard code and you seem to have to work this hard code list in the edit view controller? 

    Is that my issue that I am trying to use database and should just hard code the nine values is 9 values too many for the mvc to handle? 

    Is that why they show only hard coded examples in the help files and never how users can edit them because it not the ideal way??

    Last question does this operation require a view model?

    Wednesday, May 26, 2021 2:38 PM
  • User475983607 posted

    I illustrated how to select an option in your other recent thread.  Also, it confusing why you keep going back to the manually building a List<SelectListItem> when the SelectList has the same capability.  SelectList is less code and less room for you to mess it up. 

    The SelectList overload shown below creates an internal List<SelectListItem> and sets the selected option to SelectValueID.  Please note the Function returns a defined type.  You keep forgetting the return type in your recent threads.

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return New SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    Now that the SelectList is built, all you have to do is pass the SelectList via the ViewBag which I think we've covered to death at this point.

    ViewBag.CODE_REF_LOV_TBL_ID = GET_SELECTED_CODE_REF_VALUE(YourIdVariableGoesHere)

    The last step is writing the View markup.  The syntax depends, somewhat, on the View design.

    If you have not defined a @ModelType then use the DropDownList() helper.

    @Html.DropDownList("CODE_REF_LOV_TBL_ID ")

    If you defined a @ModelType and you want to use a parameter you defined in the @ModelType, then use the DropDownListFor() helper.  My @ModelType has a property named CODE_REF_LOV_TBL_ID.  I'm not sure what property name you're currently are using. 

    <div>
        @Html.DropDownListFor(Function(m) m.CODE_REF_LOV_TBL_ID, CType(ViewBag.CourseID, SelectList))
    </div>

    Unfortunately, there's no way to know if db.CODE_REF_LOV_TBL returns values, if the result set contains "CODE_REF_ID" and "CODE_DESCRIPTION" columns, or if there are any other coding issues.   I recommend using the Visual Studio debugger if your results are unexpected.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 26, 2021 6:00 PM
  • User2130491911 posted

    mgebhard

    I illustrated how to select an option in your other recent thread.  Also, it confusing why you keep going back to the manually building a List<SelectListItem> when the SelectList has the same capability.  SelectList is less code and less room for you to mess it up. 

    The SelectList overload shown below creates an internal List<SelectListItem> and sets the selected option to SelectValueID.  Please note the Function returns a defined type.  You keep forgetting the return type in your recent threads.

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    Now that the SelectList is built, all you have to do is pass the SelectList via the ViewBag which I think we've covered to death at this point.

    ViewBag.CODE_REF_LOV_TBL_ID = GET_SELECTED_CODE_REF_VALUE(YourIdVariableGoesHere)

    The last step is writing the View markup.  The syntax depends, somewhat, on the View design.

    If you have not defined a @ModelType then use the DropDownList() helper.

    @Html.DropDownList("CODE_REF_LOV_TBL_ID ")

    If you defined a @ModelType and you want to use a parameter you defined in the @ModelType, then use the DropDownListFor() helper.  My @ModelType has a property named CODE_REF_LOV_TBL_ID.  I'm not sure what property name you're currently are using. 

    <div>
        @Html.DropDownListFor(Function(m) m.CODE_REF_LOV_TBL_ID, CType(ViewBag.CourseID, SelectList))
    </div>

    Unfortunately, there's no way to know if db.CODE_REF_LOV_TBL returns values, if the result set contains "CODE_REF_ID" and "CODE_DESCRIPTION" columns, or if there are any other coding issues.   I recommend using the Visual Studio debugger if your results are unexpected.

    There is so much here so please bare with me. But at this point I just want to abadon this dropdownlist thing as this is why I have avoided using this for so long. It beyond complex. I have no Idea about "Also, it confusing why you keep going back to the manually building a List<SelectListItem> when the SelectList has the same capability."

    Microsoft made that an issue as they give no clear reason why you should use one over the other. So thinks for letting me know they are different. The reason I guess I am using selectlistitem as that it sounds like it is what I want to do do. I want to select and item for a list. Why would microsoft create something line this seem dumb. 

    So you are saying I should change the code I have? Let me be clear my select list thing is working . The drop down works in create view and it shows my list on screen and I am able to select an item and store it to database.

    My current problem is that I would like that value that is stored to a line item in the database to be pulled up and push to the screen inside of the dropdown list  control so when the user is in edit mode the default item for a lack of better phrasing is the first thing they see inside of the control and not the first item that is in the list .

    So if you can forget my other questions from the past. 

    How can  I use what I have to just make that little thing happen can this not happen with the select list item?

    I am not stuck on using select list item I just don;t understand why it seems to work but just not render to the screen. There are no compile errors.

    Also why does the data for the dropdown have to be converted to something else? Why does it not work as it is?? 

    Should I just not use dropdownlist for edit mode and just force the use to do it by hand?

    Again I am not opposed to following your example...I just don;t understand it at all. I don;t understand why you are asking me to change source codes that are working and doing everything I need it to do except for one thing.

    A thing that I don't  see or is even being explained how it would get a value that was stored in a database record and display it again on the edit form view.

    Again I am not stuck on the dropdownlist creation, that works I have a drop downlist on screen with items inside of it.

    I am stuck on understanding how to edit the razor edit view form where there is a drop down list on it and inside that list instead of getting a selection starting with the first item in list. I can get the drop down list tp display the value that was pulled in from database..

    Maybe what Iam trying to do is not possible and I am not explaining it correctly. Based on the videos I have been watching It appears what I am trying to do is not thing that people do. 

    They seem to only show the selected value is something you do if you want to default a dropdown to a value when you are in create view.

    So maybe that is why things are not clear because I am trying to do something that you can do with in a desktop program but may not be possible in a web program.

    Wednesday, May 26, 2021 6:36 PM
  • User2130491911 posted

    mgebhard

    Unfortunately, there's no way to know if db.CODE_REF_LOV_TBL returns values, if the result set contains "CODE_REF_ID" and "CODE_DESCRIPTION" columns, or if there are any other coding issues.   I recommend using the Visual Studio debugger if your results are unexpected.

    Yes I posted that in a post above showing the trace that shows all the values that come from the db.CODE_REF_LOV_TBL. :( 

    Maybe my post are not all showing up. About 4 or 5 post above this one I show it all and that even with ing the set of return values it even show the line item as selected true.

    I have reposted that output here

    • REF_CODES_LIST Count = 10 System.Collections.Generic.List(Of System.Web.Mvc.SelectListItem) + (0) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (1) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (2) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (3) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (4) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (5) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (6) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (7) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem + (8) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem - (9) {System.Web.Mvc.SelectListItem} System.Web.Mvc.SelectListItem Disabled False Boolean [Group] Nothing System.Web.Mvc.SelectListGroup Selected True Boolean [Text] "808 TEST" String Value "TEST" String + Raw View

     Even here on microsofts on site they do NOT show a user that editing with a dropdownlist on screen is possible sadly https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

    I think this makes it pretty clear that this can not be done

    As for the selectlistitem usage as I stated this is why I got it from microsofts very unhelpful examples 

    Also When I add a return type to the function I get the following error:

            'GET SELECTED CLE-LIST-ITEM
            Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
    
                'Get Value To Set Dropdown ID since stabase stores Description and not ID
                Dim SelectedID As Int16 = (From c In db.CODE_REF_LOV_TBL Where c.CODE_DESCRIPTION = SelectValueID Select c.CODE_REF_REC_ID).First()
    
                Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_REF_ID, .Selected = c.CODE_REF_REC_ID = SelectedID}).ToList()
    
                'See: https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/
    
    
                Return REF_CODES_LIST
    
            End Function
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30311	Value of type 'List(Of SelectListItem)' cannot be converted to 'SelectList'.	

    Wednesday, May 26, 2021 6:49 PM
  • User475983607 posted

    AppDev01

    I am stuck on understanding how to edit the razor edit view form where there is a drop down list on it and inside that list instead of getting a selection starting with the first item in list. I can get the drop down list tp display the value that was pulled in from database..

    I illustrated how to set the selected value in the example above.  I'm not sure where the selected value exists in your DB schema.  

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return New SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    If you use a List<SelectListItem> then you have loop over the list and set the selected value where the using an standard if....then or LINQ expression.   It's not hard but beyond your skill level which is why I suggested the SelectList.

    Wednesday, May 26, 2021 7:39 PM
  • User2130491911 posted

    Interesting discovery: 

    while stepping through the application the value that returns to the edit view is set to selected value is true

    (New System.Collections.Generic.Mscorlib_CollectionDebugView(Of System.Web.Mvc.SelectListItem)(ViewBag.RefCodesList).Items(9)).Selected

    But as soon as it steps in to this section 

                @Html.EditorFor(Function(model) model.Code_Reference, New With {.htmlAttributes = New With {.class = "form-control"}})
                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})

    The Expression turns red and shows up as false 

    (New System.Collections.Generic.Mscorlib_CollectionDebugView(Of System.Web.Mvc.SelectListItem)(ViewBag.RefCodesList).Items(9)).Selected

    Why would this happen in the edit view?

    Wednesday, May 26, 2021 7:46 PM
  • User475983607 posted

    while stepping through the application the value that returns to the edit view is set to selected value is true

    Correct.  That's is a basic and fundamental MVC concept found in every beginning level tutorial.

    But as soon as it steps in to this section 

                @Html.EditorFor(Function(model) model.Code_Reference, New With {.htmlAttributes = New With {.class = "form-control"}})
                @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})

    The Expression turns red and shows up as false 

    (New System.Collections.Generic.Mscorlib_CollectionDebugView(Of System.Web.Mvc.SelectListItem)(ViewBag.RefCodesList).Items(9)).Selected

    Why would this happen in the edit view?

    And I have shown you how to deal with this several times now.  Sad really.

    Wednesday, May 26, 2021 7:49 PM
  • User2130491911 posted

    mgebhard

    AppDev01

    I am stuck on understanding how to edit the razor edit view form where there is a drop down list on it and inside that list instead of getting a selection starting with the first item in list. I can get the drop down list tp display the value that was pulled in from database..

    I illustrated how to set the selected value in the example above.  I'm not sure where the selected value exists in your DB schema.  

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    If you use a List<SelectListItem> then you have loop over the list and set the selected value where the using an standard if....then or LINQ expression.   It's not hard but beyond your skill level which is why I suggested the SelectList.

    Ahhh ok now I see what you are trying to say. So that return of the selectlist is different than the select list item.

    I can see that there may be n advantage to doing it with a select list if you have a long list. 

    Let me change my source codes to see if this works . As my understanding of this concept may have improved.

    When I change my function I get the following error with the function:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30109	'SelectList' is a class type and cannot be used as an expression.	

    Wednesday, May 26, 2021 7:50 PM
  • User475983607 posted

    When I change my function I get the following error with the function:

    You made a coding mistake again.  I can't read your mind or see the code.

    Wednesday, May 26, 2021 7:58 PM
  • User2130491911 posted

    AppDev01

    When I change my function I get the following error with the function:

    You made a coding mistake again.  I can't read your mind or see the code.

    I don't understand why people are not able to see what I post. 

    I put this (what you wrote)

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    I got this which I also posted : 

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30109	'SelectList' is a class type and cannot be used as an expression.	

    I am not sure How I made a mistake cutting a pasting but clearly something is a missed 

    Wednesday, May 26, 2021 8:26 PM
  • User475983607 posted

    Oh, missing the New keyword.

    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList
        Return New SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID)
    End Function

    Wednesday, May 26, 2021 8:30 PM
  • User2130491911 posted

    You did it! You made it work. 

    I am not 100% sure how this all works but it is working so to help other with this near impossible task I will try to explain this for the non-programmer out there trying to figure out these poorly described features 

    Build a list selectList and Not SelectListItem Even if you see many examples doing so as they require for loop iteration 

    I

            'GET SELECTED CLE-LIST-ITEM

    'IN THIS FUNCTION WE PASS IN THE TEXT VALUE SO THAT IT CAN BE MATCHED TO AN ITEM IN THE LIST OF VALUES
    MORMALLY AN ID WOULD BE PASSED IN.
    Function GET_SELECTED_CODE_REF_VALUE(SelectValueID As String) As SelectList 'This is due to an unusual situation since we don't store the ID This may change The CODE_DESCRIPTION, CODE_DESCRIPTION is like this for our special situation normally you would have an ID Return New SelectList(db.CODE_REF_LOV_TBL, "CODE_DESCRIPTION", "CODE_DESCRIPTION", SelectValueID) End Function

                'Return New SelectList(db.CODE_REF_LOV_TBL, "CODE_REF_ID", "CODE_DESCRIPTION", SelectValueID) is how this should look normally

    THE EDIT VIEW

            ' GET: CO/Edit/5
    'IN THIS EDIT VIEW CONTROLLER FUNCTION WE CALL THE  GET_SELECTED_CODE_REF_VALUE FUNCTION AND WE PASS INTO IT THE VALUE STORED IN THE DATABASE FOR THAT FIELD FROM THE TABLE LINE ITEM THAT WE FOUND BY USING THE RECORD ID.
    
    'THIS FUNCTION WILL POPULATE THE VIEW BAG WITH A SELECTLIST OBJECT ( ViewBag.RefCodesList) SO THAT CAN BE USED IN THE EDIT VIEW
    
            Function Edit(ByVal id As Integer?) As ActionResult
    
    
                If IsNothing(id) Then
                    Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
                End If
    
                Dim cODE_OPINIONS_TBL As CODE_OPINIONS_TBL = db.CODE_OPINIONS_TBL.Find(id)
    
                If IsNothing(cODE_OPINIONS_TBL) Then
                    Return HttpNotFound()
                End If
    
                'Populate List of Values 
                 ViewBag.RefCodesList =GET_SELECTED_CODE_REF_VALUE(cODE_OPINIONS_TBL.Code_Reference.ToString())
    
    
    
                Return View(cODE_OPINIONS_TBL)
            End Function

    IT is not 100% Clear why this works but it does For some reason you can just use the Dropdownlist an the viewbag name in quotes and the system knows to render the list with the select value that you set

        <div class="form-group">
            @Html.LabelFor(Function(model) model.Code_Reference, htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.EditorFor(Function(model) model.Code_Reference, New With {.htmlAttributes = New With {.class = "form-control"}})
               
                    @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), "-- SELECT ONE --", htmlAttributes:=New With {.class = "form-control"})
    @Html.DropDownList("RefCodesList") @*@Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, SelectList))*@ @*@Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, List(Of SelectListItem)), htmlAttributes:=New With {.class = "form-control"})*@ @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With {.Class = "text-danger"}) </div> </div>

    All thank and glory to mgebhard for sticking in there with the help.

    I don't understand it all but I now have a much better understand of the process when it comes to editing a view with a drop down list on the page. Much better then I did before.

    Thanks for the help and the patience  

    Wednesday, May 26, 2021 9:57 PM
  • User2130491911 posted

    One additional question so to save the changes made with the dropdown to the database  I am guessing a viewmodel is needed?

    It appears that the changes are not being picked up when I use this

      @Html.DropDownListFor(Function(model) model.Code_Reference, CType(ViewBag.RefCodesList, SelectList))

    But I I make a change to any of the EditorFor fields those changes get saved to the database. I am guessing the system does not see the drop downlistfor as an original object on the page view?

    Found the issue I still had the EditorFor on the page active. I guess the system gets confused when with items are on the page.

    All changes are saving 

    Wednesday, May 26, 2021 10:12 PM