locked
making a mvc Dropdownlist using Visual Basic and using the entity frame work. Please no C# code. Looking for VB.Net help RRS feed

  • Question

  • User2130491911 posted

    Dropdown list are the bane of my existence. I just don't get why the are so hard in the mvc area.

    Anyway maybe some one can tell me what I am doing wrong here.

    So I have a database and in that database I have a table that I need to be a dropdown list.

    But when I try to get it on the create form it gives me some odd error.

    My SQL Database has 2 tables 

    CODE_OPINIONS_TBL and CODE_REF_LOV_TBL 

    The CODE_OPINIONS_TBL is like the main table things get stored to and holds the data

    The CODE_REF_LOV_TBL has the information used to populate the dropdowns

    Here have a look.

    My Error:

    Server Error in '/' Application.
    The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[BFR_LOCAL_DB.CODE_REF_LOV_TBL]', but this dictionary requires a model item of type 'BFR_LOCAL_DB.CODE_OPINIONS_TBL'.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    
    Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[BFR_LOCAL_DB.CODE_REF_LOV_TBL]', but this dictionary requires a model item of type 'BFR_LOCAL_DB.CODE_OPINIONS_TBL'.
    
    Source Error:
    
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    
    Stack Trace:
    
    
    [InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[BFR_LOCAL_DB.CODE_REF_LOV_TBL]', but this dictionary requires a model item of type 'BFR_LOCAL_DB.CODE_OPINIONS_TBL'.]
       System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +187
       System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +155
       System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +78
       System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +137
       System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +384
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +97
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +843
       System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
       System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
       System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +35
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
       System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
       System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
       System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +49
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
       System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +431
       System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +75
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +158

     My Source Codes:

    This is my create view, I have made a list out of a table and I was going to pass it to a viewbag and then push that out to the form.

    But its a no go. 

            ' GET: CO/Create
            Function Create() As ActionResult
    
                'Get LOV
                'Dim customerList As List(Of SelectListItem) = GET_CODE_REF_List()
                ViewBag.RefCodesList = GET_CODE_REF_List()
    
    
                Return View()
            End Function

    This is the other part of the create view

            ' POST: CO/Create
            '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 Create(<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.CODE_OPINIONS_TBL.Add(cODE_OPINIONS_TBL)
                    db.SaveChanges()
                    Return RedirectToAction("Index")
                End If
                Return View(cODE_OPINIONS_TBL)
            End Function

    The Source codes that make the list:

            'GET CLE-LIST
            Function GET_CODE_REF_List()
    
    
                'Fetch Records From Table using EF
                Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).Take(3).ToList()
    
                'Insert The Defau't Item To the LOV
                REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
                Return View(REF_CODES_LIST)
    
            End Function

    And the create view where I need the drop down list to go

    I tried to make a view model as I have done in C# when I have tried to do drop down list but when I tried to attach the view model

    it give me more errors  that its expecting the model over the view model.

    @ModelType BFR_LOCAL_DB.CODE_OPINIONS_TBL
    
    @*@ModelType BFR_LOCAL_DB.ViewModelClass_CodeOpinions*@
    
    
    
    @Code
        ViewData("Title") = "Create"
    End Code
    
    <h2>Create</h2>
    
    @Using (Html.BeginForm())
        @Html.AntiForgeryToken()
    
        @<div class="form-horizontal">
            <h4>CODE_OPINIONS_TBL</h4>
            <hr />
            @Html.ValidationSummary(True, "", New With {.class = "text-danger"})
            <div class="form-group">
                @Html.LabelFor(Function(model) model.ID, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.ID, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.ID, "", 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.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.Chapter, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Chapter, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Chapter, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Section, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Section, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Section, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Response_Date, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Response_Date, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Response_Date, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Year, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Year, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Year, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Status, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Status, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Status, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Author, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Author, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Author, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.From, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.From, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.From, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Locality, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Locality, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Locality, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Description, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Description, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Description, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Comments, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Comments, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Comments, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Attachments, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Attachments, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Attachments, "", New With {.class = "text-danger"})
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    End Using
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    
    @Section Scripts
        @Scripts.Render("~/bundles/jqueryval")
    End Section
    

    Here is the attempted view model

    Public Class ViewModelClass_CodeOpinions
    
    
    
        Public Property ID() As Integer
        Public Property Code_Reference() As String
        Public Property Chapter() As String
        Public Property Section() As String
        Public Property Response_Date() As Nullable(Of Date)
        Public Property Year() As String
        Public Property Status() As String
        Public Property Author() As String
        Public Property From() As String
        Public Property Locality() As String
        Public Property Description() As String
        Public Property Comments() As String
        Public Property Attachments() As String
    
    
        Public Property CODE_REF_REC_ID() As Integer
        Public Property CODE_REF_ID() As String
        Public Property CODE_DESCRIPTION() As String
        Public Property CODE_REF_CAT() As String
    
    
        Public Property CODE_REF_LIST() As List(Of CODE_REF_LOV_TBL)
    
    
    
    
    
    End Class

    So Just on the surface, having down drop down list im my c# programs  (doing them in all different ways as I don;t fully understand what is happening as it is not clear from the reading and demos I am guessing that I need to:

    Tableize make the list for the List of Values

    Send that list to the view (I use viewbags as that is the only thing I actually understand as I can see the progression from the control to the view because the same identifier is used  In control Viewbag.X on the view Viewbag.X that makes since as its like a holder. Trying to put in in the model is way to complex for me to understand. 

    nex Mod the viw so that the field is a dropdownlist and link it to the view bag. 

    Again on the surface it seems straight forward but something in this mess makes LOV difficult, And I feel I am not the only based on all the attempts out there to explain them and no one in the example make business seem to get it right.

    I have tried converting the C# Examples to vb.net code but still something is a miss.

    Not sure of anyone can help but if you can I would applicate it.

    Thursday, May 13, 2021 8:13 PM

Answers

  • User2130491911 posted

    AppDev01

    I did go through those. For some reason and english is not my main language but I am saying that the tutorial does not at least from what I could find have anything in there based on what I was trying to do. I was trying to use the entity frame work

    The tutorial illustrates how to populate a select using Entity Framework and LINQ.   Given your response, it is hard to believe that you actually went through the entire tutorial.   

    Trust me I did... even before you listed it. I have read and tried so much stuff and it always ends the same. It does not work as listed.

    I think when advance programmers offer their time help the forget not everyone interpret things the same. What may be clear to you could be beyond obscure to me.

    That is the case for most of these tutorials they show you one way that has NOTHING to do with what is trying to be accomplished.

    If dropdownlist were easy in C-sharp and VB.net the interenets would not be loaded with the same questions over and over with 10 billion different answers where some work but most don't.

    I have worked a good bit through these help pages and non of them show how a user would take data from EF and push it to the form.

    WHen I transpose what is on the tutorials on to my application I still get errors. That is not something that I am making up. I am looking at the screen and it's saying hey they stuff they are showing you does not work here. 

    So thanks for trying. But my users will just have to type in the field because I know editorfor works and it will record to the database. I will just list the options on screen for the user to type in as my solution. I know when I have been beaten lol!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 18, 2021 8:55 PM
  • User2130491911 posted

    Gosh no! No argument. Just pointing out there is nothing like what you are talking about on any of that link. I am not rushing through anything. I just can't find what it is you are claim is there. Maybe you know the direct page?

    I did a search and that is what I came up with... (The Cascading thing)

    I am not aimless I am trying to find a solution to a very difficult concept. Dropdownlist are NOT easy in mvc. in fact there are overly complicated. They are hard to make the are are to bind and they are even harder to edit. So what you call aimless I call difficult concepts. 

    If you think there is something there about dropdownlist and how to bind them to EF I would be MORE THAN grateful for a link directly to that page. All I am seeing is pure micrsoft garbage code that shows me nothing that would be useful. 

    But that's okay if you can't as that is not your job. 

    I have found some page  on another site that is more sympathetic to the plight. This writer seems to understand that is is far harder a concept than it needs to be and list in detail how to do somethings. Although not perfect the help link is actually relevant to the actual question that was being asked . Which I understand may be too simple for you to understand since your knowledge is so far advance that you may not be able to even grasp how someone would not know what you know about this stuff which I guess stupid or unwilling  or however you put it. 

    You are smart I guess I am not. This stuff is not easy and posting irrelevant links does not help. (I'm sure you mean well) I post the link below in an effort to help people that may run into the same problem I did trying to find out how to make dropdownlist.  I don;t have it figured out just yet. Now I need to find out the difference between selectlist and selectlistitem as well as find about what enumerable means.

    Then hopefully I can find out how this would work in the edit mode of the mvc form. 

    To new or non-programmers that are trying to get dropdownlist concept understanding see this link ignore the other links above

    https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 19, 2021 4:40 PM

All replies

  • User475983607 posted

    There are several approaches for creating a select list.  IMHO, the easiest is populating a SelectList type using the constructor.  The first argument is the list of items (a basic EF Query), the second is the value column name that has the option value, and the third is the text that shows in the select.  I think you'll be interested in reading the reference documentation which explains the constructor overloads.

        Public Class BasicFormController
            Inherits Controller
    
            Private db As New ContosoUniversity2Entities
    
            ' GET: BasicForm
            Function Index() As ActionResult
    
                ViewBag.CourseID = New SelectList(db.Courses, "CourseID", "Title")
                Return View()
    
            End Function
    
    
            ' POST: BasicForm/Index
            <HttpPost()>
            Function Index(CourseID As String) As ActionResult
    
                ViewBag.CourseId = New SelectList(db.Courses, "CourseID", "Title", CourseID)
                Return View()
    
            End Function
        End Class

    The View use the standard DropDownList helper.  The first argument matches the ViewBag item CourseId.

    @Code
        ViewData("Title") = "Index"
    End Code
    
    <h2>Index</h2>
    
    <form method="post">
        <div>
            @Html.DropDownList("CourseID")
        </div>
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>
    

    The error you are receiving is due to defining the View's model as BFR_LOCAL_DB.CODE_OPINIONS_TBL but passing a different type; List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL).  The two types must match.

    Thursday, May 13, 2021 10:03 PM
  • User2130491911 posted

    Hi there,

    So this part is what's confusing:

    The error you are receiving is due to defining the View's model as BFR_LOCAL_DB.CODE_OPINIONS_TBL but passing a different type; List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL).  The two types must match.

    Why would that even change when the view has the the table it was built on as the view model and all I did was make a function that made a list that would pass that object back to the the form?

    Then When I attempted to make a view model that included what I thought would be the list and all the other fields it then tells me an error saying that the view was expected BFR_LOCAL_DB.CODE_OPINIONS_TBL but was passed a viewmodel ViewModel XXX In your example you are not having to mess with the form's viewmodel at all.

    It's shocking to me that something so common is so hard to do. I will give your suggestion a try. Many thank!

    Friday, May 14, 2021 2:08 PM
  • User-474980206 posted

    What is shocking is you have not yet learned to pass function/method parameters or assign variables correctly. In strongly typed languages the types must match. While razor is a template language, it does not change the rules for variable assessments.

    Friday, May 14, 2021 2:41 PM
  • User475983607 posted

    AppDev01

    So this part is what's confusing:

    mgebhard

    The error you are receiving is due to defining the View's model as BFR_LOCAL_DB.CODE_OPINIONS_TBL but passing a different type; List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL). The two types must match.

    Why would that even change when the view has the the table it was built on as the view model and all I did was make a function that made a list that would pass that object back to the the form?

    In MVC, you get to create a strongly typed View.  The @ModelType tells the View what data to expect.  It also provides intellisense within the View editor which makes life easier for the programmer.

    @ModelType BFR_LOCAL_DB.CODE_OPINIONS_TBL

    An Action that calls the View must pass a type that matches the @ModelType.   For some unknown, reason, rather than passing a BFR_LOCAL_DB.CODE_OPINIONS_TBL type to the View you passed a List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL) type.  I'm not sure why you are passing the wrong type to the View.   Think of this programming patterns as the round peg must go in the round hole. 

    AppDev01

    Then When I attempted to make a view model that included what I thought would be the list and all the other fields it then tells me an error saying that the view was expected BFR_LOCAL_DB.CODE_OPINIONS_TBL but was passed a viewmodel ViewModel XXX In your example you are not having to mess with the form's viewmodel at all.

    MVC provides several options for passing data to a View.  The Model is one way.  Another is the ViewBag.  IMHO, it is easier to pass select options using the ViewBag because the @Html.DropDownList looks for the ViewBag key (dynamic dictionary) as illustrated above.  Again, this makes life easier for the programmer.

    AppDev01

    It's shocking to me that something so common is so hard to do. I will give your suggestion a try.

    Level of difficulty is perspective and experience.  I'm shocked that you have such a hard time with MVC.  This is not out first conversation on this subject.

    Friday, May 14, 2021 2:47 PM
  • User2130491911 posted

    Hi, 

    What do you mean? I did not change any thing. I simply made a function that made a list and tried to pass that list to the form via a viewbag.

    I did not change any types. I did not mod any thing. 

    Not to go round and round in a dumb fight but. mvc has so many technologies wrapped into it that non of it is real clear.

    Drop down list should not require all the work that it seems. For a long time I have been trying to wrap my had around this witchcraft.

    But it pretty difficult where there is very very poor examples by microsoft of what is actually going on.

    Monday, May 17, 2021 3:02 PM
  • User2130491911 posted

    Hi, 

    Or wrote:

    For some unknown, reason, rather than passing a BFR_LOCAL_DB.CODE_OPINIONS_TBL type to the View you passed a List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL) type.  I'm not sure why you are passing the wrong type to the View.   Think of this programming patterns as the round peg must go in the round hole. 
    
    
    

    That was not my intent . I wanted to get a the list back to the razor form so that I can populate a drop down list. I thought I stated that in my question. Sorry If I fail to do so,

    I have no idea why the program thanks I am trying to change the underlying form table. I thought you could send a view bag back, Had no idea that sending a viewbag back would change the view model of the table.  

    Sadly for me dropdown list is the mvc are really challenging for me. Yeah MVC is very difficult for me as again I am used to objects and things that are traceable and make sense.

    I feel like in the source code I provide that I was on the right path but maybe the wrong track.

    I made the list and now I need to pass that list back to the form. I mean is that the general concept?

    Or am I also wrong there.

    I also attempted to add a list to the view model it hopes that it would work and when I change the @model to the view model it broke everything else.

    I have spend a week look at as many example that I could find in VB and they all do something different but are very poor in explaining things.

    Examples I tried:

    https://www.aspsnippets.com/Articles/Bind-Populate-ComboBox-using-Entity-Framework-in-Windows-Forms-using-C-and-VBNet.aspx

    https://www.aspsnippets.com/Articles/Populate-Bind-DropDownList-from-database-using-Entity-Framework-in-ASPNet-MVC.aspx

    https://www.mikesdotnetting.com/article/263/migrating-from-razor-web-pages-to-asp-net-mvc-5-data-access-and-view-models

    https://www.mikesdotnetting.com/article/252/mvc-5-with-ef-6-in-visual-basic-advanced-entity-framework-scenarios

    So may be these site have lead ma wrong. Thus the Round Hole and Wrong Peg.

    Monday, May 17, 2021 3:07 PM
  • User2130491911 posted

    mgebhard

    You have this

        Public Class BasicFormController
            Inherits Controller
    
            Private db As New ContosoUniversity2Entities
    
            ' GET: BasicForm
            Function Index() As ActionResult
    
                ViewBag.CourseID = New SelectList(db.Courses, "CourseID", "Title")
                Return View()
    
            End Function
    
    
            ' POST: BasicForm/Index
            <HttpPost()>
            Function Index(CourseID As String) As ActionResult
    
                ViewBag.CourseId = New SelectList(db.Courses, "CourseID", "Title", CourseID)
                Return View()
    
            End Function
        End Class
    @Code
        ViewData("Title") = "Index"
    End Code
    
    <h2>Index</h2>
    
    <form method="post">
        <div>
            @Html.DropDownList("CourseID")
        </div>
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>

    What is the difference between what you have done and what I have done?

            'GET CLE-LIST
            Function GET_CODE_REF_List()
    
    
                'Fetch Records From Table using EF
                Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).Take(3).ToList()
    
                'Insert The Defau't Item To the LOV
                REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
                Return View(REF_CODES_LIST)
    
            End Function

    How has this some how changed the view model of my razor form? This code above is making the drop down list.

    Also How is this bit of source code changing the view model?? I have not down anything to the original view model.

    What I thought was suppose to happen here is that the view bag was passed back to the razor form to be use as a dada source for 

    the dorpdown list o f values. 

            ' GET: CO/Create
            Function Create() As ActionResult
    
                'Get LOV
                'Dim customerList As List(Of SelectListItem) = GET_CODE_REF_List()
                ViewBag.RefCodesList = GET_CODE_REF_List()
    
    
                Return View()
            End Function

    The error you are receiving is due to defining the View's model as BFR_LOCAL_DB.CODE_OPINIONS_TBL but passing a different type; List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL).  The two types must match.

    So when I get this error

    The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[BFR_LOCAL_DB.CODE_REF_LOV_TBL]', but this dictionary requires a model item of type 'BFR_LOCAL_DB.CODE_OPINIONS_TBL'.

    This is saying that the table does not have a field that is a list. So if I create a view model that has a field that can be a list to replace the the base table  This should work correct?

    Monday, May 17, 2021 3:24 PM
  • User475983607 posted

    What is the difference between what you have done and what I have done?

    Your GET_CODE_REF_LIST function returns a View.

            'GET CLE-LIST
            Function GET_CODE_REF_List()
    
    
                'Fetch Records From Table using EF
                Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).Take(3).ToList()
    
                'Insert The Defau't Item To the LOV
                REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
                Return View(REF_CODES_LIST)
    
            End Function

    Perhaps return a list of List(Of CODE_REF_LOV_TBL).

     'GET CLE-LIST
    Function GET_CODE_REF_List() AS List(Of CODE_REF_LOV_TBL)
    
        'Fetch Records From Table using EF
        Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).Take(3).ToList()
    
        'Insert The Defau't Item To the LOV
        REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
        Return REF_CODES_LIST
    End Function

    Monday, May 17, 2021 3:35 PM
  • User-474980206 posted

    ViewBag (or non-dynamic ViewData) is how data is passed to view. There is a special ViewBag.Model entry that is set when the controller passes a model to view via the

      return View(myModel)

    a view just compiles into a .net class. in the view the @model directive create a strongly typed property for ViewBag.Model. it will throw an error if the type of the passed model does not match when referenced.

    note: the html helper binder looks in several places for a value, viewbag, viewbag.model, local variable or the route data  collection.

    While I always use the For version of any html helper I use, under the covers they all call the same code.

    Monday, May 17, 2021 3:49 PM
  • User2130491911 posted

    mgebhard

    There are several approaches for creating a select list.  IMHO, the easiest is populating a SelectList type using the constructor.  The first argument is the list of items (a basic EF Query), the second is the value column name that has the option value, and the third is the text that shows in the select.  I think you'll be interested in reading the reference documentation which explains the constructor overloads.

        Public Class BasicFormController
            Inherits Controller
    
            Private db As New ContosoUniversity2Entities
    
            ' GET: BasicForm
            Function Index() As ActionResult
    
                ViewBag.CourseID = New SelectList(db.Courses, "CourseID", "Title")
                Return View()
    
            End Function
    
    
            ' POST: BasicForm/Index
            <HttpPost()>
            Function Index(CourseID As String) As ActionResult
    
                ViewBag.CourseId = New SelectList(db.Courses, "CourseID", "Title", CourseID)
                Return View()
    
            End Function
        End Class

    The View use the standard DropDownList helper.  The first argument matches the ViewBag item CourseId.

    @Code
        ViewData("Title") = "Index"
    End Code
    
    <h2>Index</h2>
    
    <form method="post">
        <div>
            @Html.DropDownList("CourseID")
        </div>
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>

    The error you are receiving is due to defining the View's model as BFR_LOCAL_DB.CODE_OPINIONS_TBL but passing a different type; List(Of BFR_LOCAL_DB.CODE_REF_LOV_TBL).  The two types must match.

    So the example you show above which I assume is the microsoft examples which I have never found very helpful as they never show any real world uses or even any thing related to the code their there wizard generates. But looking at examples I have found this

                    @Html.DropDownListFor(Function(model) model.Code_Reference, SelectList(ViewBag.RefCodesList, "CODE_REF_REC_ID", "CODE_DES"))

    IBut Of course I get an error that is pretty cryptic. 

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30109	'SelectList' is a class type and cannot be used as an expression.	BFR_LOCAL_DB	C:\APP_DEV\BFR_LOCAL_DB\BFR_LOCAL_DB\Views\CO\Create.vbhtml	35	Active
    

    I have tried a few other suggestions to get the list to render to the form

              @Html.DropDownListFor(Function(model) model.Code_Reference, (IEnumerable < SelectList >)ViewBag.RefCodesList, "CODE_REF_REC_ID", "CODE_DES"))

    THis which the x. (lambda) will not resolve. Does anyone know what gives?

    @Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

    What is sad is that I am following this example in which I assume is supposed to work. But Like most examples. 

    They don't.

    https://www.compilemode.com/2016/01/bind-dropdownlist-using-viewbag-in-asp-net-mvc.html

    What gives in programmer where people publish stuff that is fails to work  LOL>?

    Tried this: 

                    @Html.DropDownListFor(Function(model) model.Code_Reference, ViewBag.RefCodesList, "CODE_REF_REC_ID", "CODE_DES"))

    And Get this Error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30519	Overload resolution failed because no accessible 'DropDownListFor' can be called without a narrowing conversion:
        Extension method 'Public Function DropDownListFor(Of String)(expression As Expression(Of Func(Of CODE_OPINIONS_TBL, String)), selectList As IEnumerable(Of SelectListItem), optionLabel As String, htmlAttributes As Object) As MvcHtmlString' defined in 'SelectExtensions': Argument matching parameter 'selectList' narrows from 'Object' to 'IEnumerable(Of SelectListItem)'.
        Extension method 'Public Function DropDownListFor(Of String)(expression As Expression(Of Func(Of CODE_OPINIONS_TBL, String)), selectList As IEnumerable(Of SelectListItem), optionLabel As String, htmlAttributes As IDictionary(Of String, Object)) As MvcHtmlString' defined in 'SelectExtensions': Argument matching parameter 'selectList' narrows from 'Object' to 'IEnumerable(Of SelectListItem)'.
        Extension method 'Public Function DropDownListFor(Of String)(expression As Expression(Of Func(Of CODE_OPINIONS_TBL, String)), selectList As IEnumerable(Of SelectListItem), optionLabel As String, htmlAttributes As IDictionary(Of String, Object)) As MvcHtmlString' defined in 'SelectExtensions': Argument matching parameter 'htmlAttributes' narrows from 'String' to 'IDictionary(Of String, Object)'.	BFR_LOCAL_DB	C:\APP_DEV\BFR_LOCAL_DB\BFR_LOCAL_DB\Views\CO\Create.vbhtml	33	Active
    

    Tired this example as well: https://www.aspsnippets.com/Articles/Populate-Bind-DropDownList-from-ViewBag-in-ASPNet-MVC.aspx

    It appears that my application does now like the keyword select list.

    Any insight would be appreciated thanks!

    Monday, May 17, 2021 8:33 PM
  • User475983607 posted

    You did not follow the original code or instructions. 

    Below is an example using the DropDownListFor helper.  The DropDownListFor requires a strongly typed View which is added to the example.  You should be able to compare this new example with the previous.  

    Namespace Controllers
    
        Public Class CourseModel
            Public Property CourseID As Integer
        End Class
        Public Class BasicFormController
            Inherits Controller
    
            Private db As New ContosoUniversity2Entities
    
            ' GET: BasicForm
            Function Index() As ActionResult
    
                ViewBag.CourseID = New SelectList(db.Courses, "CourseID", "Title")
                Return View()
    
            End Function
    
    
            ' POST: BasicForm/Create
            <HttpPost()>
            Function Index(CourseID As String) As ActionResult
    
                ViewBag.CourseId = New SelectList(db.Courses, "CourseID", "Title", CourseID)
                Return View()
    
            End Function
        End Class
    End Namespace
    @ModelType Controllers.CourseModel
    @Code
        ViewData("Title") = "Index"
    End Code
    
    <h2>Index</h2>
    
    <form method="post">
        <div>
            @*@Html.DropDownList("CourseID")*@
        </div>
        <div>
            @Html.DropDownListFor(Function(o) o.CourseID, CType(ViewBag.CourseID, SelectList))
        </div>
        <div>
            <input id="Submit1" type="submit" value="submit" />
        </div>
    </form>
    

    AppDev01

    It appears that my application does now like the keyword select list.

    Any insight would be appreciated thanks!

    You are using C# casting constructs not VB.NET.  See the VB.NET programming guide for proper syntax.

    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/implicit-and-explicit-conversions

    Lastly, I think it is important to mention I'm using the ContosoUniversity tutorial which I asked you to go through a few months ago.  That way the community and you can have the same code base to draw examples from.  

    Monday, May 17, 2021 9:22 PM
  • User2130491911 posted

    Are you sure I am using C#? 

    I am getting all of these examples from VB.net examples. I don;t think what I am trying to do is possible sadly. 

    And I am okay with that. I am guessing that using EF and Vb.net are not something that can be done since MS has decided to pull support of VB.net which is sad.

    I see examples where they have used all of the following and on there examples they use selectlist 

    But maybe there is something wrong with my application that is preventing dropdowns from appearing on razer pages 

    You always throw me for a look when you write about strongly typed. Is there a way to do that with out it being strongly typed? THat may make it easier to understand.

    WHen I followed you example all I got was the name name of the table repeated over and over again. What I would like to happen is that the ID gets selected to that it can be stored to the database and that the description is displayed.

    I thought view models was hard. But dropdownlist are pure insanity lol.

    If it can't be down I will just require the users to type in the fields.  I am okay with that. I just thought based on all the example showing this as something that you use to be able to do that it could be done.

    Again I am using EF and I have a function that makes the select list . I would like that select list to be used on the create form so that the user can select it and store it to Database. 

    The example code is that you provide is nothing like the code I provide and it does not help. It only adds to the confusion as it is very different.

    THanks all the same 

                    @Html.DropDownList("RefCodeList", ViewBag.RefCodesList)
                    @*@Html.DropDownList("FruitId", SelectList(ViewBag.Fruits, "FruitId", "FruitName"), "Please select", New { @id = "ddlFruits" })
            @Html.DropDownListFor(Function(model) model.Code_Reference, ViewBag.RefCodesList, "CODE_REF_REC_ID", "CODE_DES"))
            @Html.ValidationMessageFor(Function(model) model.Code_Reference, "", New With {.Class = "text-danger"})*@

    May be it will help if I posted my corrected code that makes the list as I did have a error before that someone here on the site found.

            'GET CLE-LIST
            Function GET_CODE_REF_List() As List(Of CODE_REF_LOV_TBL)
    
    
                'Fetch Records From Table using EF
                Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).Take(3).ToList()
    
                'Insert The Defau't Item To the LOV
                REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
                Return (REF_CODES_LIST)
    
            End Function

    This makes the list.

    This code is the create and this is how I was hoping to get the list to the razor page

            ' GET: CO/Create
            Function Create() As ActionResult
    
                'Get LOV
                'Dim customerList As List(Of SelectListItem) = GET_CODE_REF_List()
                ViewBag.RefCodesList = New SelectList(GET_CODE_REF_List())
    
    
                Return View()
            End Function

    This seems to pass the view bag with the listed items back to the razor page... so at this step it is a green light

    It is on the razor create page page where the word selectlist does not work and it yields error  

                    @Html.DropDownList("RefCodeList", ViewBag.RefCodesList)

    I have red like under the keyword dropdownlist, this is error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30519	Overload resolution failed because no accessible 'DropDownList' can be called without a narrowing conversion:
        Extension method 'Public Function DropDownList(name As String, optionLabel As String) As MvcHtmlString' defined in 'SelectExtensions': Argument matching parameter 'optionLabel' narrows from 'Object' to 'String'.
        Extension method 'Public Function DropDownList(name As String, selectList As IEnumerable(Of SelectListItem)) As MvcHtmlString' defined in 'SelectExtensions': Argument matching parameter 'selectList' narrows from 'Object' to 'IEnumerable(Of SelectListItem)'.	BFR_LOCAL_DB	C:\APP_DEV\BFR_LOCAL_DB\BFR_LOCAL_DB\Views\CO\Create.vbhtml	34	Active
    

    As you can see your example code is nothing like my example so it is very confusion. 

    So even when I type this:

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

    I just get the table name listed over and over again which is sad.

    Monday, May 17, 2021 9:45 PM
  • User475983607 posted

    AppDev01

    Are you sure I am using C#? 

    Yes, I'm positive.  The syntax below is a C#, incorrect but C#, not VB.NET.  

    @Html.DropDownListFor(Function(model) model.Code_Reference, (IEnumerable < SelectList >)ViewBag.RefCodesList, "CODE_REF_REC_ID", "CODE_DES"))

    AppDev01

    You always throw me for a look when you write about strongly typed. Is there a way to do that with out it being strongly typed? THat may make it easier to understand.

    My original code example did not use a strong type on purpose as I know strong types confuse you.  Unfortunately, you shared an example that requires a strong type.  So, I made an VB.NET Html.DropDownListFor example with the strong type.

    AppDev01

    The example code is that you provide is nothing like the code I provide and it does not help. It only adds to the confusion as it is very different.

    Again, that's why I asked you to make effort to go through the ContosoUniversity tutorial  not only would it give you very needed experience, the community can share the same code base to draw examples from.  Anyway, I provided two working examples and several links.  I'm not sure what else I can do for you.

    Monday, May 17, 2021 10:01 PM
  • User2130491911 posted

    Hi Thanks,

    I have used those tutorials but I think the point you are missing is that they only show you how to build these list manually as hard coded list.

    I need to get this text value thing using entity frame work.

    I see the error in my list creator. So I am trying to fix it:

            'GET CLE-LIST
            Function GET_CODE_REF_List() As List(Of CODE_REF_LOV_TBL)
    
    
                'Fetch Records From Table using EF
                Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).ToList()
    
                Dim REF_CODE_LIST2 As List(Of SelectListItem) = (From CODES In db.CODE_REF_LOV_TBL 
    
    
                'Insert The Defau't Item To the LOV
                REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
                Return (REF_CODES_LIST)
    
            End Function

    The first one REF_CODES_LIST when I step into it it only shows the table names and not Value and Text.

    So I assume I need to use this SelectListItem. But I am having a hard time finding and VB.Net example of how to build that.

    Not using hard coded list but using ef in VB.net.

    If you have an link that shows that I may be on my way to a solution for this monumental task. Thanks!

    You see all these example are all manual list. Why would anyone think this would be helpful???

    https://www.webcodeexpert.com/2015/01/multiple-ways-to-generate-dropdownlist.html

    Every example is manual it like database don't exist to these people. I don;t see how you programmer keep 

    your sanity. Its like they make it purposely hard to understand this stuff.   No matter how much you study lol

    Anyway if you have any insight how how one would use EF and to make the proper list I would be very appreciative for the help!

    Monday, May 17, 2021 10:22 PM
  • User475983607 posted

    I have used those tutorials but I think the point you are missing is that they only show you how to build these list manually as hard coded list.

    I need to get this text value thing using entity frame work.

    Wrong again.  The code I shared clearly and openly is using Entity Framework.  Good luck.  

    Tuesday, May 18, 2021 12:12 AM
  • User2130491911 posted

    No I don't think I am wrong mate, 

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

    It may have been a long while since you looked at that very unhelpful tutorial, more microsoft garbage if I'm honest. It adds more confusion then help. When you search for dropdowns it is totally no related to EF so I am not sure what you are trying to show me there. But I will ask again In the source code I provide is that the correct track? Should I use selectlistitem vs select list? 

    I have the dropdown working but it is showing table name over and over vs the text and value elements, So that means I have some something right as well as done something wrong. Maybe you can provide guidance on that vs trying to confuse some one with strong typing which I have no idea what you mean and clearly that is not important since it's not required. But I am trying to keep this simple.

    But yeah those links have nothing to do with dropdowns, Unless I am translating incorrectly  but thanks anyway. I guess this is why people don't like VB.net lol

    And thanks for the luck, I am going to need it.

    Tuesday, May 18, 2021 2:49 PM
  • User-474980206 posted

    using the dropdownlist is fairly trivial.

    using a framework like MVC requires some background knowledge (often missing from vb programmers). there are common design patterns used in object oriented langauges. several of these patterns are used in MVC

    some of the patterns you should know:

    • the interface design pattern (considered a best product for object oriented langauges). this requires understanding
    • inversion of control pattern
    • singleton pattern
    • factory / builder pattern
    • and of course the MVC pattern

    if you have not studied design patterns you should. your question also show a poor understanding of class definitions, types, interfaces and method overloading. You also do not seem to understand the concept of collection interfaces.

    you should read and fully understand the following before going further

      https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/

    Tuesday, May 18, 2021 3:26 PM
  • User2130491911 posted

    Hi Bruce thanks I have asked a much clearer question.

    "using the dropdownlist is fairly trivial." Well that's not true... just do a internet's search and you will see just as many questions about dropdownlist as you would find about anything else. Lets face mvc is not easy to understand as it is a bunch wacky technologies smashed together into a mess. mvc should be call Makeit Very Confusing. LOL 

    I doubt the issue has anything to do with the talented VB.Programmers that are out there... I mean really How Rude! To cast such a wide net is lame and closed minded as well is elitist. Your C skills don't make you better than an equally talented VB programmer ! Most vb programmers know both languages. Clearly you are good at what you do and that is great but IF think you are better at what you do because the next man or women learned on a more verbose platform makes them lesser is very condescending and wrong . I do hope that is not the case as I do applicate your help about you can stow that attitude mister! 

    There is no place for Tribalism on a computer programming forum!  

    You listed a bunch a stuff that I have no idea what you are talking about is it does not relate to the question I asked.

    For some reason when I post on here the code I post gets ignored by some and instead of help I get unwanted opinions about  what I should know. Sorry to disappoint but I'm not a programmer I just write programs that get the job done that needs to be done. It's not pretty it may not follow patterns or practices but its the best that can be done by following the horrid examples microsoft post and passing them off as helpful. And the lack of vb.net examples is horrible so that's why people like me come to places like this to seek help not bs.

    Sorry bruce but your post was out of line sir.

    Tuesday, May 18, 2021 4:28 PM
  • User475983607 posted

    But I will ask again In the source code I provide is that the correct track? Should I use selectlistitem vs select list? 

    I'm confused.  I recommend the SelectList and provided two examples using the SelectList.    

    I have the dropdown working but it is showing table name over and over vs the text and value elements, So that means I have some something right as well as done something wrong. Maybe you can provide guidance on that vs trying to confuse some one with strong typing which I have no idea what you mean and clearly that is not important since it's not required. But I am trying to keep this simple.

    I'll assume this code returns more than one table column and the columns you want are CODE_REF_REC_ID and CODE_DESCRIPTION.

    'GET CLE-LIST
    Function GET_CODE_REF_List() As List(Of CODE_REF_LOV_TBL)
        'Fetch Records From Table using EF
        Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).ToList()
        'Insert The Defau't Item To the LOV
        REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
        Return (REF_CODES_LIST)
    End Function

    Then the Action is simply

    ' GET: CO/Create
    Function Create() As ActionResult
        ViewBag.RefCodesList = New SelectList(GET_CODE_REF_List(), "CODE_REF_REC_ID", "CODE_DESCRIPTION")
        Return View()
    End Function

    The View.

    @Html.DropDownList("RefCodesList")

    There's no way for me to verify your code works properly and why I've asked you go through the tutorial.  Then we would have the same data and models.  

    Tuesday, May 18, 2021 4:35 PM
  • User2130491911 posted

    I did go through those. For some reason and english is not my main language but I am saying that the tutorial does not at least from what I could find have anything in there based on what I was trying to do. I was trying to use the entity frame work

    Correction:

    I see the EF part did not change. Sorry 

    I have mis-read the example 

    Tuesday, May 18, 2021 5:29 PM
  • User475983607 posted

    I did go through those. For some reason and english is not my main language but I am saying that the tutorial does not at least from what I could find have anything in there based on what I was trying to do. I was trying to use the entity frame work

    The tutorial illustrates how to populate a select using Entity Framework and LINQ.   Given your response, it is hard to believe that you actually went through the entire tutorial.   

    Tuesday, May 18, 2021 7:17 PM
  • User2130491911 posted

    Hi mgebhard,

    When I used the following:

                ViewBag.RefCodesList = New SelectList(GET_CODE_REF_List(), "CODE_REC_ID", "CODE_DESCRIPTION")

    I get this error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30519	Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
        'Public Overloads Sub New(items As IEnumerable, selectedValue As Object, disabledValues As IEnumerable)': Argument matching parameter 'items' narrows from 'Object' to 'IEnumerable'.
        'Public Overloads Sub New(items As IEnumerable, dataValueField As String, dataTextField As String)': Argument matching parameter 'items' narrows from 'Object' to 'IEnumerable'.	BFR_LOCAL_DB	C:\APP_DEV\BFR_LOCAL_DB\BFR_LOCAL_DB\Controllers\COController.vb	39	Active
    

    What in the word is the computer talking about when it states "without a narrowing conversion" so maybe VB.net is unable to use select list features? 

    Tuesday, May 18, 2021 8:48 PM
  • User2130491911 posted

    AppDev01

    I did go through those. For some reason and english is not my main language but I am saying that the tutorial does not at least from what I could find have anything in there based on what I was trying to do. I was trying to use the entity frame work

    The tutorial illustrates how to populate a select using Entity Framework and LINQ.   Given your response, it is hard to believe that you actually went through the entire tutorial.   

    Trust me I did... even before you listed it. I have read and tried so much stuff and it always ends the same. It does not work as listed.

    I think when advance programmers offer their time help the forget not everyone interpret things the same. What may be clear to you could be beyond obscure to me.

    That is the case for most of these tutorials they show you one way that has NOTHING to do with what is trying to be accomplished.

    If dropdownlist were easy in C-sharp and VB.net the interenets would not be loaded with the same questions over and over with 10 billion different answers where some work but most don't.

    I have worked a good bit through these help pages and non of them show how a user would take data from EF and push it to the form.

    WHen I transpose what is on the tutorials on to my application I still get errors. That is not something that I am making up. I am looking at the screen and it's saying hey they stuff they are showing you does not work here. 

    So thanks for trying. But my users will just have to type in the field because I know editorfor works and it will record to the database. I will just list the options on screen for the user to type in as my solution. I know when I have been beaten lol!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 18, 2021 8:55 PM
  • User-474980206 posted

    I get this error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	BC30519	Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
        'Public Overloads Sub New(items As IEnumerable, selectedValue As Object, disabledValues As IEnumerable)': Argument matching parameter 'items' narrows from 'Object' to 'IEnumerable'.
        'Public Overloads Sub New(items As IEnumerable, dataValueField As String, dataTextField As String)': Argument matching parameter 'items' narrows from 'Object' to 'IEnumerable'.	BFR_LOCAL_DB	C:\APP_DEV\BFR_LOCAL_DB\BFR_LOCAL_DB\Controllers\COController.vb	39	Active

    What in the word is the computer talking about when it states "without a narrowing conversion" so maybe VB.net is unable to use select list features? 

    in simple terms, there are interfaces. they define a strongly typed methods. overloads are when a there is more than one version of a method name, each which distinct parameters, which must vary by number or type (called the signature). any class that implements an interface can be cast to that interface.

    I have no idea what type GET_CODE_REF_LIST() is, but it is not its not a List(), or any implementation of the interface IEnumerable(). The error says given the data types of your 3 parameters, the compiler can find not a matching overload, as the first parameter must implement IEnumerable.

    again you seems to not know what interfaces and overloads are, or even understand types and type casting. This should have been coved in a beginners VB.net course. 

    Tuesday, May 18, 2021 10:40 PM
  • User2130491911 posted

    I posted what I had in the first post of this post so it's not about not knowing its about it not working. Again The dig about what should be covered and what should be know. People all over the world seem to ask the same question and people seem to be helpful in their answers vs taking digs. 

    News flash not everyone understands everything. What may seem basic to you may be very complex to some one else. I can just look at the interenets landscape of all the question I see on this top and know I am not the only person that has issues with drops down's lets be real they are very complex in the mvc. Being this is my first mvc with vb,net it makes it even harder to get because people don;t do that many real world examples.

    Not only that for some reason when people do examples of dropdown list they also seem to fail to do examples of dorpdown list that come from database. They all seem to be manual hard code. Seriously what good is that? Just another lazy example by microsoft as most people get their data from database sources.

    I will post codes again maybe the can be looked at vs being ignored and posting about some very unhelpful microsoft tutorial that is not actually relevant to the actual question being asked.

    The Function used to create the list: It here in the box below:

            'GET CLE-LIST
            Function GET_CODE_REF_List()
    
    
                'Fetch Records From Table using EF
                'Dim REF_CODES_LIST As List(Of CODE_REF_LOV_TBL) = (From CODE In db.CODE_REF_LOV_TBL Select CODE).ToList()
    
    
                'Insert The Defau't Item To the LOV
                'REF_CODES_LIST.Insert(0, New CODE_REF_LOV_TBL With {.CODE_REF_REC_ID = "0", .CODE_DESCRIPTION = "PLEASE SELECT"})
    
    
                'To Make the Dropdown helper work in VB.net the stuff above does not work because it is missing the select list.
                'Dim REF_CODES_LIST = (From c In db.CODE_REF_LOV_TBL Select New SelectListItem With {.Text = c.CODE_DESCRIPTION, .Value = c.CODE_REF_REC_ID}).ToList()
    
                'Because the existing database stores the text / description and not the ID the Text and Value will be the same
                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()
    
                Return REF_CODES_LIST
    
            End Function

    This is in the create controller: First Create the happens when the user first loads create page

            ' GET: CO/Create
            Function Create() As ActionResult
    
                'Get LOV
                'Dim customerList As List(Of SelectListItem) = GET_CODE_REF_List()
                ViewBag.RefCodesList = GET_CODE_REF_List()
    
    
                Return View()
            End Function

    THis is the second create controller that runs when the user goes to store value to data base. These all work

            ' POST: CO/Create
            '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 Create(<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
    
                ViewBag.RefCodesList = GET_CODE_REF_List()
    
                If ModelState.IsValid Then
                    db.CODE_OPINIONS_TBL.Add(cODE_OPINIONS_TBL)
                    db.SaveChanges()
    
    
                    Return RedirectToAction("Index")
    
                End If
                Return View(cODE_OPINIONS_TBL)
            End Function

    Both have the ViewBag.RefCodesList = GET_CODE_REF_List() to get the list from the function so as of now this works as long as the user fills the fields and there are no validation errors

    What I have now discovered is that when the user goes to edit the entry on a form that list as to be loaded again in the edit controller area.

    But if you do that you lose the visual of the user selection especially if they have no plans to edit the value in the dropdown but maybe want to edit the values in other fields. I have yet to find any example addressing that issue so 

            ' 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())
    
    
                Return View(cODE_OPINIONS_TBL)
            End Function

    The Edit Save,

            ' 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

    May be you can look at my code vs ignoring it out of hand? I am close to a solution but not sure.

    I have yet for find one drop down example that shows the user how to use dropdown list in the edit view form where there is a value that was part of the database. I guess in the microsoft world that type of real world thing does not exist.

    So again say all that you will about basics and what should be know. Sorry that not real world.

    As I have stated before. I am very welling to pay a good programmer to build an example using drop downs list in the Create and edit  views that work in both VB and c-sharp

    That way I can have a real world example to draw from in the future. Are you willing to receive pay for your help bruce?

    Please let me know your price for such an example since you seem to have your pulse on how drown downs work in the mvcs

    Tuesday, May 18, 2021 11:14 PM
  • User475983607 posted

    Not only that for some reason when people do examples of dropdown list they also seem to fail to do examples of dorpdown list that come from database. They all seem to be manual hard code. Seriously what good is that? Just another lazy example by microsoft as most people get their data from database sources.

    You are not telling the truth again.  This post contains examples were the data comes from a database.    

    Tuesday, May 18, 2021 11:48 PM
  • User2130491911 posted

    I will check again because the link that was sent does not show any of that sadly. 

    Maybe I am mixing  your link up with the other users links.

    I will check it again Thanks

    Wednesday, May 19, 2021 2:41 PM
  • User2130491911 posted

    AppDev01

    Not only that for some reason when people do examples of dropdown list they also seem to fail to do examples of dorpdown list that come from database. They all seem to be manual hard code. Seriously what good is that? Just another lazy example by microsoft as most people get their data from database sources.

    You are not telling the truth again.  This post contains examples were the data comes from a database.    

    No.. just checked again and there is nothing relevant about dropdown list 

    I found this

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/ajax-control-toolkit/cascadingdropdown/using-auto-postback-with-cascadingdropdown-vb

    And the sections that follow but as i stated yesterday this is not what I am trying to do and it does not even come close to being helpful.

    There is all of this non-relevant stuffs:

    CascadingDropdown
    Filling a List Using CascadingDropDown (C#)
    Using CascadingDropDown with a Database (C#)
    Presetting List Entries with CascadingDropDown (C#)
    Using Auto-Postback with CascadingDropDown (C#)
    Filling a List Using CascadingDropDown (VB)
    Using CascadingDropDown with a Database (VB)
    Presetting List Entries with CascadingDropDown (VB)
    Using Auto-Postback with CascadingDropDown (VB)

    No nothing about EF and drop list.

    THere was this section that again years about I look through it is not  really helpful as it does not address real world situations:

    EF Database First with ASP.NET MVC
    Getting Started with Entity Framework 6 Database First using MVC 5
    Creating the Web Application and Data Models
    Generating Views
    Changing the Database
    Customizing a View
    Enhancing Data Validation

    I am not sure what it is you are still trying to show me (I do appreciate the effort but it is lost because this is stuff I did all before and it has led me to try more advance things out of necessity... so for some reason my questions get ignored you guys keep sending over these very unhelpful microsoft links that have ZERO to do with what I am asking.

    I understand that help is voluntary and not guaranteed but please stop sending me on wild chases all over the internet. If you can't help with the question that is asked PLEASE don't help at all. Thank you.

      

    Wednesday, May 19, 2021 2:55 PM
  • User475983607 posted

    AppDev01

    No.. just checked again and there is nothing relevant about dropdown list 

    Not true.  The tutorial certainly illustrates how to create and populate a SelectList.  The tutorial spans several pages.  My best guess is you are reviewing the tutorial rather than taking the time to go through each step and learn.  At least that's what your response indicate because the information is in the tutorial.  

    Your posts are full of opinion and assumptions.  As far as I can tell your only goal is to cause arguments.  Anyway, I provided multiple working examples.  I do not know what magic words you require to learn basic MVC constructs.  Frankly, learning is a problem on your end.  Perhaps find an instructor lead course to sharpen you MVC skills.

    I found this

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/ajax-control-toolkit/cascadingdropdown/using-auto-postback-with-cascadingdropdown-vb

    And the sections that follow but as i stated yesterday this is not what I am trying to do and it does not even come close to being helpful.

    You need a cascading dropdown???  It seems like you are aimlessly copying code from the internet without any real direction.  

    Wednesday, May 19, 2021 3:02 PM
  • User2130491911 posted

    Gosh no! No argument. Just pointing out there is nothing like what you are talking about on any of that link. I am not rushing through anything. I just can't find what it is you are claim is there. Maybe you know the direct page?

    I did a search and that is what I came up with... (The Cascading thing)

    I am not aimless I am trying to find a solution to a very difficult concept. Dropdownlist are NOT easy in mvc. in fact there are overly complicated. They are hard to make the are are to bind and they are even harder to edit. So what you call aimless I call difficult concepts. 

    If you think there is something there about dropdownlist and how to bind them to EF I would be MORE THAN grateful for a link directly to that page. All I am seeing is pure micrsoft garbage code that shows me nothing that would be useful. 

    But that's okay if you can't as that is not your job. 

    I have found some page  on another site that is more sympathetic to the plight. This writer seems to understand that is is far harder a concept than it needs to be and list in detail how to do somethings. Although not perfect the help link is actually relevant to the actual question that was being asked . Which I understand may be too simple for you to understand since your knowledge is so far advance that you may not be able to even grasp how someone would not know what you know about this stuff which I guess stupid or unwilling  or however you put it. 

    You are smart I guess I am not. This stuff is not easy and posting irrelevant links does not help. (I'm sure you mean well) I post the link below in an effort to help people that may run into the same problem I did trying to find out how to make dropdownlist.  I don;t have it figured out just yet. Now I need to find out the difference between selectlist and selectlistitem as well as find about what enumerable means.

    Then hopefully I can find out how this would work in the edit mode of the mvc form. 

    To new or non-programmers that are trying to get dropdownlist concept understanding see this link ignore the other links above

    https://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 19, 2021 4:40 PM
  • User475983607 posted

    Gosh no! No argument. Just pointing out there is nothing like what you are talking about on any of that link. I am not rushing through anything. I just can't find what it is you are claim is there. Maybe you know the direct page?

    I do know the page.  It happens to be the last page of the tutorial which covers Entity Framework patterns

    Now you'll add a drop-down list to the Courses Index page so that users can filter for a particular department. You'll sort the courses by title, and you'll specify eager loading for the Department navigation property.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/advanced-entity-framework-scenarios-for-an-mvc-web-application#examine-sql-sent-to-database

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

    Thanks!! I did not see that at all and its buried but thank you I will see if it is helpful.

    Wednesday, May 19, 2021 8:57 PM