locked
Trying to get some basic understanding of this arcane and dark art called view models, example on the question. RRS feed

  • Question

  • User2130491911 posted

    I have a very hard time understanding the concept of view models in mvc as the concept does not make much sense to me.

    In the past I have just tied to do everything in sql server when it came to views and getting database data set like I need it,

    This current project this does not seem possible and may require this view model concept.

    I have 10 small database tables... so my first question is can View Models contain more than one table??

    If so How are these tables populated??

    This the view model that I put together from the items (.cs files) that make up the edmx file

    There are the so called partial Classes that were there.

    Please.... take a look

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace XXX_XXXX_XXX.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
            [NotMapped]
            public List<CONTACT_LOCATION_TBL> CONTACT_LOCATION_LOV { get; set; }
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
        }
    }

    First is this correct that the view model is a group of collected tables via the partial classes that the edmx wizard made? ?

    And how do you populate these tables so that it can be used? I mean there are like 8 table in this one class?

    Thanks in advance!

     

    Tuesday, June 23, 2020 6:06 PM

Answers

  • User2130491911 posted

    Oh my goodness,,, I  finally found an answer that makes sense...

    I post here to help any future user... 

    https://stackoverflow.com/a/39419543

    I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...
    
    If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).
    
    I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).
    
    

    I want to confirm this... but if this is the case I get it... If this was TSQL te edmx cs files are the way your mvc application see the database  but this so call view model is some sort of selection of data from the data base that you can do stuff with...

    So guess you can combine tables together ?

    there is still some clearly needed at this point I will just make a new thread with a more focus question set.. but this makes me happy to finally find a non technical answer. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2020 12:15 AM
  • User475983607 posted

    Or maybe my visual studio is buggered out??  But something is broken. 

    There is nothing wrong with Visual Studio and nothing is broken except your understanding.   It's truly baffling that you make the same coding mistakes over and over,

    public ActionResult Question_Intake()
    {
        RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
        using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities())
        {
            RMRP_DDL_VM.CountyLocationDropDownList = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "LOCATION");
        }
        return View(RMRP_DDL_VM);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 6, 2020 5:51 PM

All replies

  • User475983607 posted

    Typically, a view model is defined by application requirements.  For example, a user account page might contain several feature; update profile picture, change password, update address, and update contact information.  This information can exist in several different locations but the data is needed in one View.  That's all a view model is.  The data needed to build a View (the UI) according to application specifications.  

    The next step is populating the view model which can be done many ways.   You might call a web service, call an ADO.NET data access layer, write a LINQ to Entity query, maybe the data comes form several different APIs or several service calls.  It depends how your application is designed but you should know how to get the data.

    It is important to note that a view model is not an EDMX entity. 

    Tuesday, June 23, 2020 7:09 PM
  • User-474980206 posted

    you are confusing the view models with entity models.

    view models are a data structure for views and controller to pass messages to each other. the controller constructs a model to pass to the view. the view post sends post back data to the controller (usually bound to an action parameter - called the post back view).

    it is also popular to use a databinding technique with sql queries usually performed by a ORM, like EF or dapper. More current ORM use POCO objects. These are called entity objects or models, and are used to pass data to and from an ORM library.

    Simple examples tend to use the entity object as the view model because in trivial examples they are one for one. But in general this is a bad practice. The view model should be structured for what is to be displayed in the view.

    Tuesday, June 23, 2020 7:40 PM
  • User1120430333 posted

    First is this correct that the view model is a group of collected tables via the partial classes that the edmx wizard made?

    No, your understanding is not correct,  and you are confused as so many are concerning this. You are trying to make the persistence model a viewmodel. The EF an ORM and a persistence framework,  works with a persistence model.

    https://en.wikipedia.org/wiki/Persistence_framework

    The persistence model is not a domain model either that many are confused about.

    http://blog.sapiensworks.com/post/2012/04/07/Just-Stop-It!-The-Domain-Model-Is-Not-The-Persistence-Model.aspx

    A viewmodel object  is dedicated  or strong typed to a cshtml view. The viewmodel  object's job is to work with the cshtml view. The viewmodel object can be populated by  a persistence model object. A  viewmodel object can populate a persistence model object that works with persistence framework to be persisted to a database.  

    A viewmodel can be populated from many datasources such as persistence model objects.

    https://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc

    Tuesday, June 23, 2020 7:44 PM
  • User2130491911 posted

    This is a very confusing concept. So is there some basic way to make this digestible?  I think what I am reading (the links left by the people trying to help. The things that I am reading and watching... no one seems make an example that makes this concept clear.

    So lets forgo the data population part. Is there a non-technical way to explain this view model concept... for example the a Hello World type of thing. 

    Every one is saying that I am mixing up concept x with concept why.

    But IF you look at what is in the edmx file created by the wizards 

    //------------------------------------------------------------------------------
    // <auto-generated>
    //    This code was generated from a template.
    //
    //    Manual changes to this file may cause unexpected behavior in your application.
    //    Manual changes to this file will be overwritten if the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------
    
    namespace RMRP_SELF_ASSESSMENT
    {
        using System;
        using System.Collections.Generic;
        
        public partial class LOCATION_LOV
        {
            public int ID { get; set; }
            public string Location { get; set; }
        }
    }
    

    When you look an example for how to make a view model it basically shows that they took what was in this .cs file under the xXX_Model.edmx tab and put it into a folder named viewmodels and made a class with that same information inside of it.

    So I took my files that were under the edmx tabs and made my own:"

    I put this is a folder that I called ViewModels (as seen in some examples) and I copied and paste all the elements in the tables listed in the .cs files under the edmx tab

    Now I have the following: As listed before but now I move the thing for the list of values to be under the tables they need to get their data from

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
                [NotMapped]
                public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
                [NotMapped]
                public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
    
    
    
        }
    }

    So now in the controller I have this bit 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
                VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
    
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList<LOCATION_LOV>(); 
    
                }
    
                    return View();
            }
        }
    }

    But this give me and error stating 

    Severity Code Description Project File Line Suppression State
    Error CS1061 'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?) RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 21 Active

    This error is just a bunch of mumbo jumbo as everything it claims its missing is there... 

    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList<LOCATION_LOV>(); 

    Inside the CSHTML file I have the following 

                @Html.DisplayNameFor(model => model.LOCATION_LIST_LOV)
                @Html.DropDownListFor(model => model.LOCATION_LIST_LOV, new SelectList(Model.LOCATION_LIST_LOV, "ID", "LOCATION"), "Select Your Location")

    It gives errors the same mumbo jumbo error.. 

    At the top of the page there is this

    @model RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class

    I mean microsoft needs to try to figure out how to explain this voodoo nonsense... where it makes sense for the masses... I mean clearly you guys get it... but this is just dumb that in there own examples they can't even make this stuff some what clearer to help users under stand it.

    I guess it's back to trying to make my views in SQL vs the view model horror show.

    Tuesday, June 23, 2020 9:05 PM
  • User475983607 posted

    AppDev01

    Severity Code Description Project File Line Suppression State
    Error CS1061 'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?) RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 21 Active

    This error is just a bunch of mumbo jumbo as everything it claims its missing is there... 

    LOCATION_LIST_LOV is a nested class within VM_RMRP_QUESTIONS_Class.  LOCATION_LIST_LOV is not a property of VM_RMRP_QUESTIONS_Class which is how you are trying to use it.

    @Html.DisplayNameFor(model => model.LOCATION_LIST_LOV)

    AppDev01

    I mean microsoft needs to try to figure out how to explain this voodoo nonsense... where it makes sense for the masses... I mean clearly you guys get it... but this is just dumb that in there own examples they can't even make this stuff some what clearer to help users under stand it.

    The error message is very clear.  It's telling you, Hey, I can't find the LOCATION_LIST_LOV property.  Maybe you're missing a reference.  It's up to you to understand basic C# syntax and recognize that you have class declarations not property definitions.

    Fix your class definition.  I did the first one.

     public class VM_RMRP_QUESTIONS_Class
        {
            public CONTACT_LOCATION_NUMBER_TBL CONTACT_LOCATION_NUMBER_TBL  { get; set;}
        }
    
        public partial class CONTACT_LOCATION_NUMBER_TBL
        {
            public string LOCATION_ID { get; set; }
            public string CONTACT_NUMBER { get; set; }
    
            [NotMapped]
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
        }

    However, it still seems like you are confusing Entities with a View Model.

    Tuesday, June 23, 2020 9:20 PM
  • User1120430333 posted

    When you look an example for how to make a view model it basically shows that they took what was in this .cs file under the xXX_Model.edmx tab and put it into a folder named viewmodels and made a class with that same information inside of it.

     My first issues and where you would never pass a code review I was involved in is you're doing direct database access in the controller, becuase you are not following MVC principles that are easy to break with ASP.NET MVC. The PayrollVM is being worked with by the PayrollDM's object methods  being used by the PayrollController. Go to the bottom of the post and read what it is talking about. 

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    Yes I am using EF, but for me, EF is not even in the ASP.NET MVC project. EF is in a classlib project DAL  and DTO(s) are being used between the DAL and the ASP.NET MVC project. 

    using Microsoft.AspNetCore.Mvc.Rendering;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace PublishingCompany.Models
    {
        public class PayRollVM
        {
            public class Payroll
            {
                public int PayrollId { get; set; }
                public int AuthorId { get; set; }
                public string AuthorFirstName { get; set; }
                public string AuthorLastName { get; set; }
    
                [Required(ErrorMessage = "Author is required")]
                public string AuthorTypeId { get; set; }
    
                [Required(ErrorMessage = "Salary is required")]
                public int? Salary { get; set; }
    
                public List<SelectListItem> AuthorTypes { get; set; } = new List<SelectListItem>();
    
            }
            public List<Payroll> Payrolls { get; set; } = new List<Payroll>();
        }
    }
    
    using ServiceLayer;
    using System.Linq;
    using Entities;
    using Microsoft.AspNetCore.Mvc.Rendering;
    
    namespace PublishingCompany.Models
    {
        public class PayRollDM : IPayRollDM
        {
            private IPayRollSvc svc;
            private IAuthorSvc svcauth;
            public PayRollDM(IPayRollSvc payRollSvc, IAuthorSvc authorSvc)
            {
                svc = payRollSvc;
                svcauth = authorSvc;
            }
    
            public PayRollVM GetAll()
            {
                var vm = new PayRollVM();
    
                var dtos = svc.GetAll().ToList();
    
                vm.Payrolls.AddRange(dtos.Select(dto => new PayRollVM.Payroll()
                {
                    PayrollId = dto.PayrollId,
                    AuthorId = dto.AuthorId,
                    AuthorFirstName = dto.AuthorFirstName,
                    AuthorLastName = dto.AuthorLastName,
                    Salary = dto.Salary
                }).ToList());
    
                return vm;
            }
    
            public PayRollVM.Payroll Find(int id)
            {
                var dto = svc.Find(id);
    
                var payroll = new PayRollVM.Payroll
                {
                    PayrollId = dto.PayrollId,
                    AuthorId = dto.AuthorId,
                    AuthorFirstName = dto.AuthorFirstName,
                    AuthorLastName = dto.AuthorLastName,
                    Salary = dto.Salary
                };
    
                return payroll;
            }
            public bool BlnFindPayRollByAuthorId(int id)
            {
                bool blnflag = false;
    
                var dto = svc.FindPayRollByAuthorId(id);
    
                if (dto.PayrollId != 0)
                {
                    blnflag = true;
                }
    
                return blnflag;
            }
            public PayRollVM.Payroll Add()
            {
                return PopulateSelectedList( new PayRollVM.Payroll());
            }
    
            public void Add(PayRollVM.Payroll payroll)
            {
                var dto = new DtoPayroll
                {
                    AuthorId = int.Parse(payroll.AuthorTypeId),
                    Salary = payroll.Salary
                };
    
                svc.Add(dto);
            }
    
            public PayRollVM.Payroll Update(int id)
            {
                var dto = Find(id);
    
                var payroll = new PayRollVM.Payroll
                {
                    PayrollId = dto.PayrollId,
                    AuthorId = dto.AuthorId,
                    AuthorFirstName = dto.AuthorFirstName,
                    AuthorLastName = dto.AuthorLastName,
                    Salary = dto.Salary
                };
    
                return payroll;
            }
    
            public void Update(PayRollVM.Payroll payroll)
            {
                var dto = new DtoPayroll
                {
                    PayrollId = payroll.PayrollId,
                    AuthorId = payroll.AuthorId,
                    Salary = payroll.Salary
                };
    
                svc.Update(dto);
            }
    
            public void Delete(int id)
            {
                var dto = new DtoId
                {
                    Id = id
                };
    
                svc.Delete(dto);
            }
    
            public PayRollVM.Payroll PopulateSelectedList(PayRollVM.Payroll payroll)
            {
                var dtos = svcauth.GetAuthorTypes().ToList();
    
                payroll.AuthorTypes.AddRange(dtos.Select(dto => new SelectListItem()
                {
                    Value = dto.Value,
                    Text = dto.Text
                }).ToList());
    
                var selected = (from a in payroll.AuthorTypes.Where(a => a.Value == payroll.AuthorTypeId) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return payroll;
    
            }
        }
    }
    
    @model  PayRollVM.Payroll
    
    <!DOCTYPE html>
    
    <style type="text/css">
        .editor-field > label {
            float: left;
            width: 150px;
        }
    
        .txtbox {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            background: white;
            color: black;
            cursor: text;
            border-bottom: 1px solid #104A7B;
            border-right: 1px solid #104A7B;
            border-left: 1px solid #104A7B;
            border-top: 1px solid #104A7B;
            padding-top: 10px;
        }
    </style>
    <html>
    <head>
        <title>Create</title>
    </head>
    
    <body>
        <h1>Author Payroll</h1>
    
        @using (Html.BeginForm())
        {
    
            @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    
    <fieldset>
    
        <legend>Create</legend>
    
        @Html.HiddenFor(model => model.PayrollId)
        @Html.HiddenFor(model => model.AuthorId)
    
    <div class="form-group">
        <div class="editor-field">
            @Html.Label("Author:")
            @Html.DropDownListFor(m => m.AuthorTypeId, Model.AuthorTypes, "Select....")
        </div>
    </div>
    <div class="form-group">
        <div class="editor-field">
            @Html.Label("Salary:")
            @Html.TextBoxFor(model => model.Salary)
            @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
        </div>
     </div>
        <br />
        <p>
            <input type="submit" name="submit" value="Save" />
            <input type="submit" name="submit" value="Cancel" />
        </p>
    
    </fieldset>
        }
    
    </body>
    </html>
    
    
    
    using Microsoft.AspNetCore.Mvc;
    using PublishingCompany.Models;
    
    namespace PublishingCompany.Controllers
    {
        public class PayRollController : Controller
        {
            private IPayRollDM pdm;
            public PayRollController(IPayRollDM payRollDM)
            {
                pdm = payRollDM;
            }
            public IActionResult Index()
            {
                return View(pdm.GetAll());
            }
    
            public IActionResult Detail(int id = 0)
            {
                return id == 0 ? null : View(pdm.Find(id));
            }
    
            public ActionResult Create()
            {
                return View(pdm.Add());
            }
    
            [HttpPost]
            public ActionResult Create(PayRollVM.Payroll payroll, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
                
                if (!ModelState.IsValid) return View(pdm.PopulateSelectedList(payroll));
    
                if (pdm.BlnFindPayRollByAuthorId(int.Parse(payroll.AuthorTypeId)))
                {
                    ModelState.AddModelError(string.Empty, "Author has an existing PayRoll record.");
                }
    
                if (!ModelState.IsValid) return View(pdm.PopulateSelectedList(payroll));
    
                pdm.Add(payroll);
                return RedirectToAction("Index");
            }
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(pdm.Update(id));
            }
    
            [HttpPost]
            public ActionResult Edit(PayRollVM.Payroll payroll, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                if (!ModelState.IsValid) return View(payroll);
    
                pdm.Update(payroll);
                return RedirectToAction("Index");
            }
            public IActionResult Delete(int id = 0)
            {
                if (id > 0) pdm.Delete(id);
    
                return RedirectToAction("Index");
            }
    
            public ActionResult Cancel()
            {
                return RedirectToAction("Index", "Home");
            }
        }
    }

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.


    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.


    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

    Tuesday, June 23, 2020 10:04 PM
  • User2130491911 posted

    Thanks all but reading all this it just make it even more clear that I will never understand view models. 

    Its all witchcraft to me sadly...  Now I am even more confused then when I started. I guess the little understanding that I did have just got wiped out by reading all of these confusing directives. 

    To the user that is stating that I am confusing some concept with another... well I am just doing what microsoft seems to be telling to do.

    There direction are not very clear... and that fine as this concept may be for more advance users.

    I am guessing there is no easy way to explain what a view model is without all of this technical jargon?

    Is there no simple way to see what a view model is? All of this stuff about this thing or that thing just has really blew my understanding of what I thought I new out of the water.

    So there is no way to say what a view model is using a real world explanation vs a super duper technical one??

    DA924 that last bit you left using the using statement is what? I have never used that before? So that just helps me realize that you guys may be to advance to explain to someone that does not understand what you are trying to explain. (not your issue... mine clearly)

    I guess I will just have to hard code the list of values as that makes more sense to me. Or turn the project over to a more senior developer.

    Thanks to those that have attempted to help.

    If anyone else has a better way of explaining please fill free to chime in. As It would be nice to get a list of values from the database vs having to hard code 100 items.

    Thanks again! 

    I put the so-called view model back the way I had it ... what concept am I confusing??? Is this a view model or is it not a view model? 

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
    
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
            [NotMapped]
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
    
        }
    }

    Having it back this way there are no compile errors at least.

    UhOh... I typed to soon I am now getting this Error... I tell this thing is something else.

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	21	Active
    

    After more messing around this is what I have in the controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
    
    
                VM_RMRP_QUESTIONS_Class.LOCATION_LOV LOV_LOCATION = new VM_RMRP_QUESTIONS_Class.LOCATION_LOV(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList<LOCATION_LOV>();
                }
    
                    return View();
            }
        }
    }

    THis are the errors:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	22	Active
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1061	'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Views\QA_RMRP\Question_Intake.cshtml	138	Active
    

    This is in the CSHTML File

                <div>Please select your city/county:  </div>
                <br />
                @Html.DisplayNameFor(model => model.LOCATION_LIST_LOV)
                @Html.DropDownListFor(model => model.LOCATION_LIST_LOV, new SelectList(Model.LOCATION_LIST_LOV, "ID", "LOCATION"), "Select Your Location")
    
                <br />

    I get this error for the code above:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error CS1061 'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?) RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Views\QA_RMRP\Question_Intake.cshtml 139 Active

    There has to be a way to get a simple drop down list... can I do this with out a view model???

    This dumb error claims "  'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV'

    Umm silly computer its all here  the section is right here in the file:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
                [NotMapped]
                public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
    
            }
    

    So I am not sure what more this silly thing wants!?

    Wednesday, June 24, 2020 6:19 PM
  • User2130491911 posted

    Ok I made some progress... I guess... 

    I am down to one error message... 

    But again its very cryptic (of Course)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
    
    
                VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList<LOCATION_LOV>();
                }
    
                    return View();
            }
        }
    }

    This is the error Now... the level of difficulty to get a list of values displayed beggers belief! 

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	22	Active
    

    Wednesday, June 24, 2020 7:35 PM
  • User-474980206 posted

    You errors have nothing to do with the concept of a view model, which is just a class instance (parameter) passed to a view, but understanding of c# types. C# is a strongly typed language that require types to match when an assignment is done.

    you should lean C# better before attempting mvc which requires you understand types, interfaces, generics, anonymous types, and lambda functions. Also most samples will include linq code, and if you use linq to sql or ef a basic understanding of expression trees is handy.

    Also helpful is to learn some design pattern like inversion of control, interface design, etc.

       https://www.dofactory.com/net/design-patterns

    Wednesday, June 24, 2020 7:38 PM
  • User2130491911 posted

    Hi Old Chum... I knew would pop in with some unhelpful helpful commentary.  My question was about view models... is spiraled into this as this is the error I have.. which I know is a basic c error.. but I am trying to figure out why. It has nothing to do with me knowing C which it pretty clear I know some c.

    As I have stated before... if you can;t help don't help... the snark comments do nothing for me. 

    IF you know why the view model is causing this error and feel like  sharing please feel free.

    IF you are just commenting just to be rude and a condescending know it it all then by all means feel free to be that as well.

    Just do it outside of threads where a user is seeking help from people that may have the ability and are willing to try to to help.

    IF logic... put that in your pipe and smoke it!

    Thanks buddy.

    Wednesday, June 24, 2020 8:10 PM
  • User2130491911 posted

    Ok maybe this will shed some light on the situation here...

    In the so-called view model. WHen I have it written like this.. I get the following error.

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1061	'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	22	Active
    

    I don't know what his is trying to tell me when I have inside of the view model what I think its asking for. (sorry I don't know how to do the highlighting)

    But its the section that has the notmapped text.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
    
    
            [NotMapped]
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
    
        }
    

    But when I changed this so-called view model to and move the unmapped element under the Area called public partial class LOCATION_LOV

    I get the following errors (4 errors vs 1)

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	22	Active
    

    And this is repeated 3 times

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1061	'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Views\QA_RMRP\Question_Intake.cshtml	138	Active
    

    When I move that line This triggers 3 errors

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
                [NotMapped]
                public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
            }
    

    Hopefully this will help someone better understand the issue that I am fighting with.

    I am stumped by this.

    Wednesday, June 24, 2020 8:34 PM
  • User1120430333 posted

    CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>' 

    You can't make one object based on its type,  a  class,  RMRP_SELF_ASSESSMENT.LOCATION_LOV be another object VM_RMRP_QUESTIONS_Class.LOCATION_LOV based on its type, a class. You can't make the cast. And it doesn't matter if both classes have the same properties.

    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList<LOCATION_LOV>();

    The above statement is invalid.

    You have to use a foreach loop and map the EF result returned from the EF query and map it to a collection of VM objects loading them into a collection.

    What you want is something similar that is happening in the below code where a list of  DTOArticles must be created from the list of EF Articles, which are two different types,  but both represent the same data. You can view the DTO class as a viewmodel class.. You have to go  into a foreach loop on the collection returned from the EF query and map each object over to a VM object and load VM oject into the VM collection.

    public List<DtoArticle> GetArticlesByAuthorId(int id)
            {
                var dtos = new List<DtoArticle>();
    
                var articles = pc.Article.AsNoTracking().Where(a => a.AuthorId.ToString().Contains(id.ToString()));
               
                foreach (var article in articles)
                {
                    var intid = (int)article.AuthorId;
    
                    var dtoauthor =  _daoAuthor.Find(intid);
    
                    var dto = new DtoArticle
                    {
                        ArticleId = article.ArticleId,
                        AuthorId = article.AuthorId,
                        AuthorName = dtoauthor.LastName +", " + dtoauthor.FirstName,
                        Title = article.Title,
                        Body = article.Body
                    };
    
                    dtos.Add(dto);
                }
                 
                return dtos;
            }

    Wednesday, June 24, 2020 8:57 PM
  • User2130491911 posted

    Hi DA924,

    What you have there is what I have done in my other project where I was not using a so called view model.

    But you are writing that this is all invalid but I am following this user here in this video... is he using something different????

    Time Indexes

    Here he is doing the thing with the class (I have the so called view model)

    https://youtu.be/ei4dOToBFxs?t=273

    Here is is setting up the dropdown list in the CSHTML

    https://youtu.be/ei4dOToBFxs?t=545

    And here the Chap is setting things up in the controller.

    https://youtu.be/ei4dOToBFxs?t=731

    So is he using magic or has something microsoft done that prevents what this chap is showing working to stop working.

    He is not using Entity Frame work or writing queries which is why I was trying to follow his approach 

    Just seeking clarity 

    Wednesday, June 24, 2020 9:09 PM
  • User1120430333 posted

    Regardless of the data source of the object you're coming from and trying to come up with an object that is needed, you can't make a 747Jet object be a 787jet object, becuase they both are two different objects with different behaviors and properties.

    787jet 787obj = 747obj;  // it is invalid.

    You can make a 787obj and map  some properties of the 747obj to the 787obj.

    But you just can't make a whole 747obj be a whole 787obj.

    And that's what you're trying to do.

    Wednesday, June 24, 2020 9:44 PM
  • User475983607 posted

    AppDev01

    Ok maybe this will shed some light on the situation here...

    In the so-called view model. WHen I have it written like this.. I get the following error.

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1061	'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' does not contain a definition for 
    'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of
    type 'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' could be found (are you missing a using directive or an assembly reference?)
    RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 22 Active

    I don't know what his is trying to tell me when I have inside of the view model what I think its asking for. (sorry I don't know how to do the highlighting)

    The error is telling you the two LOCATION_LOV types below are not the same.  You cannot equate (=) the LOCATION_LOV types.  

    List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>
    List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>

    The reason the two LOCATION_LOV types are not equal has to do with the unique namespaces.  In programming, even in c, namespaces are used to uniquely identify a type.  Think about a table.  A table can have four legs or a table can have columns and rows.   A namespaces is used to uniquely identify the different types of tables.

    Furnature.Kitchen.Table
    HTML.UI.Table

    AppDev01

    Its all witchcraft to me sadly...  Now I am even more confused then when I started. I guess the little understanding that I did have just got wiped out by reading all of these confusing directives. 

    To the user that is stating that I am confusing some concept with another... well I am just doing what microsoft seems to be telling to do.

    There direction are not very clear... and that fine as this concept may be for more advance users.

    A view model is a class consisting of only property definitions.  

        public class ExampleViewModel
        {
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_LOCATION_NUMBER_TBLs { get; set; }
        }
    
        public class CONTACT_LOCATION_NUMBER_TBL
        {
            public string LOCATION_ID { get; set; }
            public string CONTACT_NUMBER { get; set; }
        }

    View models are populated in the controller, typically by a data access layer, then passed to a view.

        public class GeneralController : Controller
        {
            // GET: General
            public ActionResult Index()
            {
                ExampleViewModel vm = PopulateViewModel();
                return View(vm);
            }
    
            public ExampleViewModel PopulateViewModel()
            {
                //Data access layer
                DbContext db = new DbContext(); 
    
                //Query the data base and return a list of CONTACT_LOCATION_NUMBER_TBL types
                List<RMRP_SELF_ASSESSMENT.ViewModels.CONTACT_LOCATION_NUMBER_TBL> 
                    contatLocations = (from c in db.CONTACT_LOCATION_NUMBER_TBL
                                        select new RMRP_SELF_ASSESSMENT.ViewModels.CONTACT_LOCATION_NUMBER_TBL()
                                        {
                                            CONTACT_NUMBER = c.CONTACT_NUMBER,
                                            LOCATION_ID = c.LOCATION_ID
                                        }).ToList();
    
                //Populate the view model
                ExampleViewModel vm = new ExampleViewModel();
                vm.CONTACT_LOCATION_NUMBER_TBLs = contatLocations;
                return vm;
            }
        }
    @model RMRP_SELF_ASSESSMENT.ViewModels.ExampleViewModel
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.CONTACT_LOCATION_NUMBER_TBLs[0].LOCATION_ID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CONTACT_LOCATION_NUMBER_TBLs[0].CONTACT_NUMBER)
            </th>
        </tr>
    
    @foreach (var item in Model.CONTACT_LOCATION_NUMBER_TBLs) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.LOCATION_ID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CONTACT_NUMBER)
            </td>
        </tr>
    }
    
    </table>
    

    I think it is important to mention that learning programming jargon will improve your experience on programming forums.  It is not the community's responsibility to figure out what programming terms and definition you understand or how you learn. 

    I provided a few links above that go to the C# programming guide.  Please make an effort to learn the terms and definitions. 
     

    Wednesday, June 24, 2020 9:51 PM
  • User-474980206 posted

    AppDev01

    Hi Old Chum... I knew would pop in with some unhelpful helpful commentary.  My question was about view models... is spiraled into this as this is the error I have.. which I know is a basic c error.. but I am trying to figure out why. It has nothing to do with me knowing C which it pretty clear I know some c.

    As I have stated before... if you can;t help don't help... the snark comments do nothing for me. 

    IF you know why the view model is causing this error and feel like  sharing please feel free.

    IF you are just commenting just to be rude and a condescending know it it all then by all means feel free to be that as well.

    Just do it outside of threads where a user is seeking help from people that may have the ability and are willing to try to to help.

    IF logic... put that in your pipe and smoke it!

    Thanks buddy.

    I not trying be snarky, I just saying in c# the following is an error

    int a;
    a = "hello"; // type error

    is a type conversion error. that what all your errors messages are.   

                  LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList<LOCATION_LOV>();

    fails because, even though the classes have the same name, they have different namespaces. simple case:

    public class foo
    {
       public class MyClass
       {
           public int MyValue {get; set;} 
       }
    }
    
    public class bar
    {
    
       public class MyClass
       {
           public int MyValue {get; set;} 
       }
    
       ..
    
       myClass bar = new MyClass { MyValue = 10}; // works 
       myClass foo = new foo.MyClass { MyValue = 10}; // type assignment error 
    }
    

    this is all C# 101, and nothing to do with view models. unlike an loosely typed language like javascript where this would work, it won't in C#. the fact that you struggle with clear error messages, means you need to study C# more.

    note: the automapper library is a solution when you want to copy classes with similar structure.

    Wednesday, June 24, 2020 10:21 PM
  • User2130491911 posted

    Thanks all... yeah is still not clear why the user in the video got his to work.

    And view models are still so confusing.. as their purpose does not seem to make any sense... why would anyone add something so complicated to there 

    program is beyond my comprehension. It amazes me that you guys seem to get it. Evidently it is an abstract concept that may just exist because it can and not because it is important or needed.

    Friday, June 26, 2020 1:31 PM
  • User1120430333 posted

    I don't see what is so hard to understand that the viewmodel is dedicated and strong typed  to the view. You populate the VM object from the persistence model object and send the VM object into the view.    In turn, the VM object can be populated by the view. The VM object is used to populate the persistence model object that is persisted to the database by the persistence framework.

    Basically,  using the VM is another form of SoC. Also it is object oriented programming 101 and the interaction of objects that any software developer using an OOP language should be able to understand.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    <copied>

    In computer science, separation of concerns (SoC) is a design principle for separating a computer program into distinct sections such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program

    <end>

    https://www.codeproject.com/articles/826417/advantages-of-viewmodel-in-mvc-model-view-controll

    <copied>

    People usually get scared and confused when they hear the word
    View Model in MVC. View Model is a hidden layer in ASP.NET MVC applications.

    View Model is not a part of MVC. It’s something brought up by community for maintaining SOC.

    SOC –Separation of concerns – It means everyone will do only that which is meant for them. In case of MVC:

    Model will handle Business logic and Business data, it won’t do anything else.
    Controller will handle only user interaction logic. User interaction logic means logic which will handle the user’s requests.
    View will contain User interface – Design with user will interact.

    Let’s understand Why ViewModel is required when SOC is already implemented in MVC and How ViewModel does that?

    <end>

    It's a very simple concept the viewmodel.

    To be blunt about it, the problem is with you AppDev01.

    Friday, June 26, 2020 3:11 PM
  • User2130491911 posted

    Thank's DA924,

    Let me be clear. I know that I am the reason why I don't understand viewmodels. Its a concept that is way over my head. It is something that I have tried to figure out for the last 4 years. I have done or tried countless examples and done a tone of tutorial (most don't work even if you type them in word for word)

    But Even in your own statement you recognize that people can be confused by them. So  I am not the only one so It's not a 101 type thing. This is high concept. And high concept can be very confusing. The concept makes not sense in a real world way as it seemingly can't really be describe in a useful basic way.

    There does not seem to be a way to really describe why you would use them. You mentioned sep of concerns... ok cool. But that does not explain what they are? People wite they are a class... okay... sure ... but why would use them?. Some one stated how they are populated but why do they exist? You already have a model?

    Why even recreate the same thing the computer has already auto generated for you? Why take something that is separated already and combine it into one...  And then trying to fine so arcane way to combine them???

    How does a view model link more than one table? And how are multiple data sources populated when you have combined everything into one file. None of it to me makes any sense and I have  invested alot of time trying to figure it out.

    Clearly its not a concept that I can understand. I am starting to realize that now. 

    It may be a 101 thing in your book but in mine, its a mind blowing concept that borders on witchcraft. Even the microsoft tutorials on the topic are nonsense as they do a very poor job in their examples.

    I am guessing in my final analysis of the topic....View models cannot be used or made to work in a drop down list as was pointed by another member attempting to help.

    And that the way the example puts it all together is wrong because of the way it is written which leads me to wonder how on earth did that guy make his example work in that video...

    Its just above my level I guess. 

    Friday, June 26, 2020 5:07 PM
  • User2130491911 posted

    Ok Reading through this is so very confusing...

    You wrote:

        public class ExampleViewModel
        {
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_LOCATION_NUMBER_TBLs { get; set; }
        }
    
        public class CONTACT_LOCATION_NUMBER_TBL
        {
            public string LOCATION_ID { get; set; }
            public string CONTACT_NUMBER { get; set; }
        }

    What is CONTACT_LOCATION_TBLs? Where did the lowercase s come from???

    Then below that your do have anything related to the lower case s

    This is your controller... I also find this very confusing as well.

    So you made a function ? 

     public ExampleViewModel PopulateViewModel()
        public class GeneralController : Controller
        {
            // GET: General
            public ActionResult Index()
            {
                ExampleViewModel vm = PopulateViewModel();
                return View(vm);
            }
    
            public ExampleViewModel PopulateViewModel()
            {
                //Data access layer
                DbContext db = new DbContext(); 
    
                //Query the data base and return a list of CONTACT_LOCATION_NUMBER_TBL types
                List<RMRP_SELF_ASSESSMENT.ViewModels.CONTACT_LOCATION_NUMBER_TBL> 
                    contatLocations = (from c in db.CONTACT_LOCATION_NUMBER_TBL
                                        select new RMRP_SELF_ASSESSMENT.ViewModels.CONTACT_LOCATION_NUMBER_TBL()
                                        {
                                            CONTACT_NUMBER = c.CONTACT_NUMBER,
                                            LOCATION_ID = c.LOCATION_ID
                                        }).ToList();
    
                //Populate the view model
                ExampleViewModel vm = new ExampleViewModel();
                vm.CONTACT_LOCATION_NUMBER_TBLs = contatLocations;
                return vm;
            }
        }

    This is my controller  and I don't have a function there and the example video I was follow did not make a function in the controller.

    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
    
    
                VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList();
                }
    
                    return View(LOV_LOCATION);
            }
        }
    }

    Is it possible there is more than one way to do this..

    I am still not seeing why my application is incorrect. You are are saying the error is clear...

    Let me ask this.. is there something that I can change with in my own example so that it can work?

                VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList();
                }

    This is where I am getting the error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	22	Active
    

    Is there something that can be changed with in the so-called view model in my example to make this work?

    Again  my so-called view model

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
    
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
            [NotMapped]
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
    
        }
    }

    Also maybe  could some one point out there I am making this error that the computer is thinking that I am making? Is it in the so-called view model? Is it in the controller? Is it in the database?

    Thanks!

    Friday, June 26, 2020 6:11 PM
  • User-474980206 posted

    view models are pretty simple. its just a object passed to the view via ViewBag.Model. The @mdel directive in the view defines the type. if you think of a view as a public method (which it compiles to) the code is like (not actual):

    public class MyView
    {
        private readonly ViewContext;
        private ViewData => ViewConext.ViewData;
        private ViewBag => ViewConext.ViewBag;
        private MyModelType Model => ViewData["Model"] as MyModelType;
    
        public MyView(ViewContext viewContext)
        {
              ViewContext = viewContext;
        }
    
        public HtmlString Render()
        {
            // compiled razor code view code 
        }
    }
    

    when your action

         return View(myModel)

    it just sets the view context.

    the the view code can access any data ViewContext, and some helper methods are generated for convenience. as the model is a C# class you can pass any data you want. you can pass additional objects via the viewbag.

    some of the things you are trying to do, copy one object type to another even though they have the same properties is just not supported by C#. other languages have this feature, but not C#. you need to use the copy syntax

    var p = await db.GetPersonAsync(id);
    model.Person
    {
       FirstName = p.FirstName,
       LastName = p.LastName,
       ....
    };
    
    // it often handy to write extension method if this need sto be done more than once"
    
    public static ViewModelPerson Copy(this ViewModelPerson v, EnitityPerson e)
    {
        v.FirstName = e.FirstName;
        v.LastName = e.LastName;
        ...
        return v;
    } 
    public static CreateViewModelPerson(this EnitityPerson e)
    {
       var v = new ViewModelPerson();
       return v.Copy(e);
    }
    
    // then above is:
    
    var p = await db.GetPersonAsync(id);
    model.Person = p.CreateViewModelPerson();
    

    its all about learning C# and how to use types. while not C# 101, it is only C# 102

    remember the view model is just to pass data to the view render method and only the data the view needs. the view should not be making database calls, network calls, etc.

    the controller get action should

        read data required for the view
        copy data to view model
        select view to use and return

    the controller post action should

        validate the posted form data
        call business processing logic
        if not successful
            read additional data required for the view
            copy data to view model
            select view to use and return
       else
            redirect to a get action

    note: I assume you have been using WebForms. There is no future there. You might be interested in Razor Pages the replacement, but it still uses models, and uses interface patterns.

    if you just want to learn the common web MVC pattern, then try ruby on rails, or node.js,  which being dynamic, are much simpler to code. 

    Friday, June 26, 2020 6:46 PM
  • User1120430333 posted

    I am guessing in my final analysis of the topic....View models cannot be used or made to work in a drop down list as was pointed by another member attempting to help.

    You are wrong, because I gave you the PayrollVM that has an  AuthorTypes, that works with  dropdownlist in the previous posted view code in this thread. But I guess you didn't bother to even look at what I posted, huh?

    To me, you have learned from the too sweet cheese cake ASP.NET tutorials where everything particularly the persistence model that the persistence framework uses is in the ASP.NET MVC project, and you have  not learn how to develop an ASP.NET MVC solution that is using a layered or n-tier architectural style where SoC has been implemented. The DTO or POCO travels through the layers or tiers,  and the EF model objects are left behind at the Data Access Layer.

    If the EF model is not in the ASP.NET MVC project the presentation layer the EF model in another layer the DAL, then what will you do?

    I guarantee you that the developers that have been in communications with you about the viewmodel know and have used the architectural styles. And they know and understand the importance of SoC being implemented in a solution. 

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    How does a view model link more than one table? And how are multiple data sources populated when you have combined everything into one file. None of it to me makes any sense and I have invested alot of time trying to figure it out.

    Example of viewmodel being populated by multiple sources with VM loaded into view.

    using System.Collections.Generic;
    using System.Runtime.Serialization;
    
    namespace Entities
    {
       [DataContract] 
        public class DTOStudent
        {
            
            private DTOResponse dtor = new DTOResponse();
    
            [DataMember]
            public Int32 StudentID { get; set; }
    
            [DataMember]
            public string LastName { get; set; }
    
            [DataMember]
            public string FirstName { get; set; }
    
            [DataMember]
            public DateTime? EnrollmentDate { get; set; }
    
            [DataMember]
            public virtual ICollection<DTOEnrollandCourse> EnrollsandCourses { get; set; }
    
            [DataMember]
            public DTOResponse DtoResponse
            {
                get { return dtor; }
                set { dtor = value; }
            } 
        }
    }
    using System;
    using System.Runtime.Serialization;
    
    namespace Entities
    {
        public class DTOEnrollandCourse
        {
            [DataMember]
            public decimal? Grade { get; set; }
    
            [DataMember]
            public string Title { get; set; }
    
            [DataMember]
            public Int32? Credits { get; set; }
        }
    }
    
    public DTOStudent GetStudentById(Int32 id)
            {
                var dto = new DTOStudent();
                using (var context = new CUDataEntities())
                {
                    var student = (context.Students.Where(a => a.StudentID == id)).SingleOrDefault();
    
                    if (student != null)
                    {
                        dto.StudentID = student.StudentID;
                        dto.FirstName = student.FirstName;
                        dto.LastName = student.LastName;
                        dto.EnrollmentDate = student.EnrollmentDate;
    
                        var enrolllments =  new DAOEnrollment().GetEntrollmentsByStudentId(id).ToList();
                        var courses = new DAOCourse().GetCoursesByStudentCourseId(student.StudentID).ToList();
    
                        dto.EnrollsandCourses = (from a in enrolllments
                                      join b in courses on a.CourseID equals b.CourseID
                        select new  DTOEnrollandCourse()
                         { Title = b.Title, Credits = b.Credits, Grade = a.Grade }).ToList();
                    }
                }
    
                return dto;
            }
    public StudentViewModels.Student GetStudentById(int id)
            {
                var dto = studapi.GetStudentById(id);
    
                var student = new StudentViewModels.Student
                {
                    StudentID = dto.StudentID,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName,
                    EnrollmentDate = dto.EnrollmentDate,
                    EnrollsandCourses = new List<EnrollandCourseViewModel.EnrollandCourse>()
                };
    
                foreach (var dtoec in dto.EnrollsandCourses)
                {
                    var ec = new EnrollandCourseViewModel.EnrollandCourse
                    {
                        Credits = dtoec.Credits,
                        Grade = dtoec.Grade,
                        Title = dtoec.Title
                    };
    
                    student.EnrollsandCourses.Add(ec);
                }
    
                return student;
            }
     public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(studmods.GetStudentById(id));
            }
    @model MVC.Models.StudentViewModels.Student
    
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <title>Details</title>
     </head>
    <body>
    <h1>Student Details</h1>
        
    @Html.Label("First Name:") @Html.DisplayFor(m => m.FirstName) <br/>
    @Html.Label("Last Name:") @Html.DisplayFor(m => m.LastName) <br/>
    @Html.Label("Enrollment Date:") @Html.DisplayFor(m => m.EnrollmentDate) <br/>
        
    <br/><br/><br/>
        
    <table class="table">
            <tr>
                <th>
                    Course Title
                </th>
                <th>
                    Grade
                </th>
                <th>
                    Credits
                </th>
            </tr>
    
            @foreach (var item in Model.EnrollsandCourses)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Grade)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Credits)
                    </td>
                </tr>
            }
        </table>
    
    
    </body>
    </html>   
        
        
    
    

    Friday, June 26, 2020 7:14 PM
  • User2130491911 posted

    Hi DA942,

    No I read and studied it but it is such a departure from what I am trying to do that I can't find a way to use your example to make my example work.

    My example is part of a project that I am working on so I can;t just erase what is done. Your method works ... I am pretty sure of that.

    I just don't understand it.

    I guess I should have wrote that My example does not allow me to link the so-called view model to a dropdown list. 

    Sorry that that was not clear...

    Friday, June 26, 2020 8:12 PM
  • User2130491911 posted

    Thanks for trying as this is too complex for me, I will just have to turn the project over to a different developers. 

    This concept is very elusive to me. Each person that left and example has left some different and now I can't process heads or tails.

    The syntax is all different . Now I am wondering why and how what I wrote even compiles as every ones example is so different from my own.

    DA924 you are using and api another users is using some abstraction it is all now just a big ol'jumble... what I thought I knew is now lost in all of this different ways to do something I guess.

    I will ask again... Just to try to steer this away from questions for my coding skill and knowledge of C and so on. I have a sample that I understand at least in it's structure... and I am trying to trouble shoot the issue with it. As stated I am not trying to write what is written unless it's totally wrong. 

    So my focus is  what is wrong with this bit? You all state that the error is that I am trying to convert a type... so with out going into the deep technical jargon about what I am doing wrong... is there a way to fix it based on the source code I provided?

    This is from the controller

      VM_RMRP_QUESTIONS_Class LOV_LOCATION = new LOCATION_LOV VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList <LOCATION_LOV>();
                }
    
                    return View(LOV_LOCATION);

    When having this as the view model? 

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
    
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
            [NotMapped]
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
    
        }
    }

    Is my issue here?  or is it in the controller?

    Is there something short of deleting this code and hanging myself with my mouse and Keyboard wires... that can fix the issue

    As I am not understanding all of the tech jargon they you are sharing about what can be wrong... as I am looking for what is wrong.

    Also To the user that stated that I was eating the sweetest of the cakes... I am just using the materials that mircosoft provided... It's their wack documentation. IF that have measure effort of trying to help people is sweet cake... my God man.. what does their healthy Fair taste like. But  seriously you can call me out on using documentation... that is a first!  I use use what is available. Maybe some of you work on teams so you can lean over to your work mate Gary and ask him for help. I have to ask the internet and I use the resources of the internet. So my Gary is a video or a tutorial when I run into a topic I don't fully understand.

    As stated each of the examples that some of you have kindly provided (I do appreciate your time and effort but it has confused me even further ) But truth be told I am truly trying to figure out why my program is not working when I followed step by step something that was shown to work.

    Thanks again all.  

    Friday, June 26, 2020 9:58 PM
  • User-474980206 posted
    VM_RMRP_QUESTIONS_Class LOV_LOCATION = new LOCATION_LOV VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList <LOCATION_LOV>();
                }

    again you can not assign different types.

       LOV_LOCATION.LOCATION_LIST_LOV is defined as List<VM_RMRP_QUSESTIONS_Class.LOCATION_LOV>  where LOCATION_LOV is a subclas defined in the view model
       RMRP_DB.LOCATION_LOV is an Querable of the LOCATION_LOV entity defined in the db context somewhere

    just because the two classes have the same name (or even the same properties) they are not the same. the trivial is to map then:

    var LOV_LOCATION = new VM_RMRP_QUESTIONS_Class();
    
    using (var RMRP_DB = new RMRP_DB_Entities())
    {
        // you don't show the entity class for RMRP_DB.LOCATION_LOV so I don't know its properties
        // but if they match the view version
    
        LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.Select(r => new VM_RMRP_QUESTIONS_Class.LOCATION_LOV 
        {
            ID = r.ID,
            Location = r.Location
        }.ToList();
    }
    
    return View(LOV_LOCATION);
    

    Not sure why LOCATION_LOV is not a collection of SelectListItem as normal coding practices would recommend. why create a collection for the view which needs to be remapped.

    again please read a C# tutorial and learn about namespaces  and sub classes (C# 101). Some basic understanding of Linq and lambdas would also help. I would recommend taking a course in C# before tackling MVC. You just don't understand the basics of the language.

    Friday, June 26, 2020 10:46 PM
  • User1120430333 posted

    I agree with the other poster. If all you were doing is trying to load a dropdownlist, then all that should have been on the VM class is a collection for the  selectlistItems populated by the result of the database query and Id property on the VM class  to hold the selected id from the dropdownlist with it having a validation required attributer for the selected id property.

    THAT'S the difference between a viewmodel class that is  strong typed to the controls on the view as opposed to making or copying the EF persistence model trying to make it a VM class sending it into the view that really has nothing to with the view. What does any of the partial classes of the class you called a VM have to do with the view?

    Friday, June 26, 2020 11:47 PM
  • User2130491911 posted

    Hi Bruce.. you wrote 

    / you don't show the entity class for RMRP_DB.LOCATION_LOV so I don't know its properties
        // but if they match the view version

    I am not sure what you mean... the RMRP_DB is the database and the .LOCATION_LOV is in the so called view model yes?

    Is this what you are writing about? If so this is in the so called view model...

            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
    
            }

    What is the entity class ?  IS that the .CS file that was created by the wizard when I made the edmx? I guess I am not understanding what I am not showing.. in  my very  first post of this post I posted the whole program... IS there something else  I can post that would help?

    Ok You wrote

    again you can not assign different types.
    
       LOV_LOCATION.LOCATION_LIST_LOV is defined as List<VM_RMRP_QUSESTIONS_Class.LOCATION_LOV>  where LOCATION_LOV is a subclas defined in the view model
       RMRP_DB.LOCATION_LOV is an Querable of the LOCATION_LOV entity defined in the db context somewhere
    
    just because the two classes have the same name (or even the same properties) they are not the same. the trivial is to map then:

    Ok let me clear up something I named those elements except for the table name.. LOCATIONS_LOV that DBA named that by mistake.. the the rest of the elements I named which is why things have similar names. Sort of self documentation. 

    I guess what I don't understand is that the sample I based this off of the presenter did the same thing...and his worked...

    That is what makes this all the more confusing How did the presenter get his work. I watched him do the same thing I did.

    Let me ask... do you think something change with in visual studio from 2017 to now that allowed for what I posted to work back

    then that does not work now?

     

    Just commentary below this line not germane to the question 

    Guys I write in c a good bit. I use lambdas  ( I admit that I still don't understand why or what it does... I just figured it was just more unnecessary typing of stuff you have in c like curly braces and semi colons.  But I know how to use them to query for linq and I have other drop down in other programs that work.

    I normally avoid so called view models because I don't grasp the concept at all. This the first time I tried to combine all the table into once so called view model.. what a horror show. Now topping that off with trying to work the complicated process of making dropdown list in mvc. 

    My Issue is really simple ( I am not expert in c) but I dont use it daily like some of you experts may. I use C, Vb.net and others.. I have had over 10k in training, some of you may say that was money wasted but those would be unkind people.

    I write decent programs ... and no I guess I would not pass a code review as someone stated in a post above But that is not the nature of the space I work in.

    My training has ranged from MVC, C , Xamirin , vb.net  etc. I am not a brilliant programmer... not trying to be. Actually  am just a dumb pilot, that when I'm not on schedule to fly... I am tasked with this stuff as I have a CompSci background. 

    So some concepts that you deem 101...  are honest gaps that occur when you stop and start back into coding. I am sure some you have even had this happen when you switch from project to project.  Its true some of the gaps come from not understanding some explanations that have never made any sense. I am not knee deep is this mess daily. I write code for my agency as a secondary consideration.

    Let me state for the record I hate MVC.. But it does the CRUD thing well so it allows for rapid builds of simple forms. But It silly to me and easy things became hard. For example making a flipping drop down list take an insane about of effort in my opinion.

    But again I do really appreciate all the attempts with helping.. So If you can take off your expert hats for a second and remove the Bias and understand you working with a dumb guy that would be awesome. 

    I know I am not entitled to be helped... just trying to maximize my understanding of a concept that you may know well but to me is voodoo nonsense because there is no basic dumb guy way to explain whats going on I'm guessing.

    Hopefully that small sample of  background helps give some POV. 

    Saturday, June 27, 2020 1:06 PM
  • User2130491911 posted

    Hi DA924 you wrote 

     If all you were doing is trying to load a dropdownlist, then all that should have been on the VM class is a collection for the  selectlistItems populated by the result of the database query and Id property on the VM class  to hold the selected id from the dropdownlist with it having a validation required attributer for the selected id property.

     Is that Not what I'm doing? I'c confused... I thought that is exactly what I am trying to do.

    I created this so called viewmodel and created what I thought was a so called collection...

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
    .
    .
    .
    .
    .
    .
    //This is from the database the DBA missed name the table
    //but this just the table we need to use as a drop doen ls
    public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
    
            }
    .
    .
    .               
    //And this bit here I thought was the collection
    
            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }

    So I am not sure what I have done wrong???

    You wrote ...

    THAT'S the difference between a viewmodel class that is  strong typed to the controls on the view as opposed to making or copying the EF persistence model trying to make it a VM class sending it into the view that really has nothing to with the view. What does any of the partial classes of the class you called a VM have to do with the view?

    So what you are saying is that clicking on make folder naming it view model and then clicking in the fold and making a class not how you make a view model?

    From microsofts on play book if I recall state that you can go into the generated files created by the wizard automatically and cut and paste these elements into you so called view model... are you stating that is not correct??

    Jesuschristi... I checking out... I done with view models... clearly the are a made up bs concept.  once that is to high level for a dumb guy... 

    Saturday, June 27, 2020 1:26 PM
  • User2130491911 posted

    Hi Bruce 

    For this section your wrote... I get the error: do I need to change something in the so called view model file?

        LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.Select(r => new VM_RMRP_QUESTIONS_Class.LOCATION_LOV 
        {
            ID = r.ID,
            Location = r.Location
        }.ToList();
    }
    Severity Code Description Project File Line Suppression State
    Error CS1026 ) expected RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 30 Active
    Error CS1061 'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' does not contain a definition for 'ToList' and no accessible extension method 'ToList' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' could be found (are you missing a using directive or an assembly reference?) RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 30 Active
    Error IDE1007 The name 'ToList' does not exist in the current context. RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 30 Active

    Once thing I noticed was when I typed .(DOT) behind this bit ... just before the ToList...

    {ID = r.ID, Location = r.Location }.ToList();

    I don't see ToList as an option... I only see 

    Equals

    Getcode

    Gettype

    ID

    Location

    ToString

    But no ToList... am I missing something somewhere?

    Update:

    Ok I was able to fix the syntax, but I am right back where I started may post ago.. I mean exactly back to where I started... this is just way too funny!!

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
    
                var LOV_LOCATION = new VM_RMRP_QUESTIONS_Class();
                using (var RMRP_DB = new RMRP_DB_Entities())
                // VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                //using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    //LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList <LOCATION_LOV>();
    
                LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.Select(r => new VM_RMRP_QUESTIONS_Class.LOCATION_LOV
                {
                    ID = r.ID,
                    Location = r.Location
                }.ToList());
    
                }
    
                    return View(LOV_LOCATION);
            }
        }
    }

    My Error which is the same here that I started with:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1061	'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' does not contain a definition for 'ToList' and no accessible extension method 'ToList' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	30	Active
    

    I give up.lol!

    There are so may edits because I am trying so may things

    So move the list part that was in the view model up some to see if that helps NOPE

            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
                [NotMapped]
                public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
    
    
            }

    I Get even more errors

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1061	'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	26	Active
    Error	CS1061	'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' does not contain a definition for 'ToList' and no accessible extension method 'ToList' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class.LOCATION_LOV' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	30	Active
    Error	CS1061	'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Views\QA_RMRP\Question_Intake.cshtml	138	Active
    Error	CS1061	'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Views\QA_RMRP\Question_Intake.cshtml	139	Active
    Error	CS1061	'VM_RMRP_QUESTIONS_Class' does not contain a definition for 'LOCATION_LIST_LOV' and no accessible extension method 'LOCATION_LIST_LOV' accepting a first argument of type 'VM_RMRP_QUESTIONS_Class' could be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Views\QA_RMRP\Question_Intake.cshtml	139	Active
    

    If I move it back out to the bottom of the so called view model to where it was. My error count drops

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public string LOCATION_ID { get; set; }
                public string CONTACT_NUMBER { get; set; }
    
    
    
            }
    
    
            public partial class CONTACT_LOCATION_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
    
    
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
    
            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    
            [NotMapped]
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
    
        }
    }

    So I assume this is making the list that the compiler can not see? What gives?

            [NotMapped]
            public List<LOCATION_LOV> LOCATION_LIST_LOV { get; set; }
    

    Its good to see that I am NOT the only one struggling with this concept... it trying is hard to wrap your head around

    https://forums.asp.net/t/2034117.aspx?Viewmodel+does+not+contain+a+defintion+for+and+no+extension+method+accepting+a+first+argument+of+type

    Saturday, June 27, 2020 2:12 PM
  • User2130491911 posted

    Ok guys I out... I know when I beaten and I have been beaten.. clearly this program I am working on is not compatible with view models or dropdown list. I can accept that. 

    Since tolist did not show up I changed toString since it did show up just see id if it would compile and I could trouble shoot from there... well trouble shot back and and boom error  city. SO I quit.  This is too stupid to continue. I will never grasp the concept of view models combined with dropdownlist. clearly I can't used both...

    Thanks anyway. My Code My Errors.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
    
                var LOV_LOCATION = new VM_RMRP_QUESTIONS_Class();
                using (var RMRP_DB = new RMRP_DB_Entities())
                // VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                //using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                    //LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList <LOCATION_LOV>();
    
                    LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.Select(r => new VM_RMRP_QUESTIONS_Class.LOCATION_LOV
                    {
                        ID = r.ID,
                        Location = r.Location
                    }.ToString()};
    
                }
    
                    return View(LOV_LOCATION);
            }
        }
    }

    Massive error explosion

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS1026	) expected	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	30	Active
    Error	CS1002	; expected	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	30	Active
    Error	CS1519	Invalid token 'return' in class, struct, or interface member declaration	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	34	Active
    Error	CS1001	Identifier expected	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	34	Active
    Error	CS1022	Type or namespace definition, or end-of-file expected	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	37	Active
    Error	CS1520	Method must have a return type	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	34	Active
    Error	CS0501	'QA_RMRPController.QA_RMRPController(LOV_LOCATION)' must declare a body because it is not marked abstract, extern, or partial	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	34	Active
    Error	CS0246	The type or namespace name 'LOV_LOCATION' could not be found (are you missing a using directive or an assembly reference?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	34	Active
    Error	CS0161	'QA_RMRPController.Question_Intake()': not all code paths return a value	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	15	Active
    

    Thanks for trying everyone!!!

    Saturday, June 27, 2020 2:46 PM
  • User-474980206 posted

    Pretty simple typo

                    }.ToString()};
    

    s/b

                    }.ToString());
    

    Most programmers learn how to balance them by counting, but the ide will even show balancing {} and ()

    Saturday, June 27, 2020 3:06 PM
  • User2130491911 posted

    I fixed that... but the poster suggested that it be ToList? I am assuming since I am trying to make a drop down list it should be list? Or will string work as well?

    My Error when changed to string

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0266	Cannot implicitly convert type 'System.Linq.IQueryable<string>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'. An explicit conversion exists (are you missing a cast?)	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	26	Active
    

    Saturday, June 27, 2020 3:18 PM
  • User1120430333 posted

    IMHO, the VM should be what is below that deals with a control or controls on the view. The VM properties are strong typed to controls and their usage on the view.  It should be that you make a new SelectListItem for each Location_Lov Id and Location you polled from the database and populate the SelectListItem value property with the Location_Lov Id and populate the text property with Location and load each item into LOCATION_LOVS.

     LOCATION_LOV_ID holds the ID of the item selected in the dropdownlist.by the user. 

    AGAIN, your copying of the EF persistence model class should never lead to the class being a VM. The VM is a class that you custom make,  and it's sole  purpose is to work with controls on the view. I can't make it any clearer than that to you.. 

    https://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
       public class LOCATION_LOV_VM
       {
           [Required(ErrorMessage = "LOCATION_LOV is required")]
    public LOCATION_LOV_ID { get; set; }
    public List<SelectListItem> LOCATION_LOVS { get; set; } } }

    Saturday, June 27, 2020 4:24 PM
  • User2130491911 posted

    why would I use a view model doe just one table.. I could just use the class that was auto generated and never have to deal with this view model non-sense...

    In the very first tutorial I did 3 years ago on view models microsoft made it seem like you would use view models to smash together different tables into one view model.

    Base on what you just wrote... that is not the case... I mean I dont need a view model for just one table.

    AGAIN, your copying of the EF persistence model class should never lead to the class being a VM. The VM is a class that you custom make,  and it's sole  purpose is to work with controls on the view. I can't make it any clearer than that to you.. 
    

    I did not copy the files when I made this nonsense view model...  I oped each file ans copied the contents out of the auto generated file and made a view model folder added a class file and paste the information into the field so to not have to have to type the same thing over again. Are you suggesting that the copy and paste is causing the issue?? Or are you thinking that I am using the auto generated  files?

    So in for opinion is  there is no way to salvage what I have done? 

    If not its fine. Some one else will just have to take over the project as I have nibbled on a big wheel of unchewables...

    It happens I am not to big to say that this is beyond my abilities... It would just be nice if microsoft made this a little more clear what view models are and how to use them.

    Also you confuse me with this part

    Saturday, June 27, 2020 11:58 PM
  • User2130491911 posted

    Oh my goodness,,, I  finally found an answer that makes sense...

    I post here to help any future user... 

    https://stackoverflow.com/a/39419543

    I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...
    
    If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).
    
    I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).
    
    

    I want to confirm this... but if this is the case I get it... If this was TSQL te edmx cs files are the way your mvc application see the database  but this so call view model is some sort of selection of data from the data base that you can do stuff with...

    So guess you can combine tables together ?

    there is still some clearly needed at this point I will just make a new thread with a more focus question set.. but this makes me happy to finally find a non technical answer. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 28, 2020 12:15 AM
  • User1120430333 posted

    Base on what you just wrote... that is not the case... I mean I dont need a view model for just one table.

    And somehow a viewmodel is solely associated with a database table? The viewmodel is an object that works with an ASP.NET MVC view. The viewmodel's data source can be from a variety of sources with a database being one of them.

    But lets not get it twisted here. You are not working with a database table. You are working with an EF entity/class/object  derived from EF's,  an ORM,  virtual database used by EF a persistence framework. 

    https://en.wikipedia.org/wiki/Persistence_framework

    https://en.wikipedia.org/wiki/Object-relational_mapping

    <copied>

    Object-relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.

    <end>

    Linq-2-Entities is being used.

    https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/linq-to-entities

    <copied>

    LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#.

    <end>

     It happens I am not to big to say that this is beyond my abilities... It would just be nice if microsoft made this a little more clear what view models are and how to use them.

    I have repeatedly told you  the purpose of the VM. I have also told you and given you a link showing you your confusion with the viewmodel object  and the persistence model object used by EF and your mistaken usage of a persistence model object using it as a VM object. 

    https://docs.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-3.1

    <copied>

    Model Responsibilities

    The Model in an MVC application represents the state of the application and any business logic or operations that should be performed by it. Business logic should be encapsulated in the model, along with any implementation logic for persisting the state of the application. Strongly-typed views typically use ViewModel types designed to contain the data to display on that view. The controller creates and populates these ViewModel instances from the model.

    View Responsibilities

    Views are responsible for presenting content through the user interface. They use the Razor view engine to embed .NET code in HTML markup. There should be minimal logic within views, and any logic in them should relate to presenting content. If you find the need to perform a great deal of logic in view files in order to display data from a complex model, consider using a View Component, ViewModel, or view template to simplify the view.

    <end>

    Also you confuse me with this part

    Lets just say that I have nothing to do with your confusion and you already had you mind made up on what you think things should be. All I and others have tried to do is open your eyes and take the blinders off, which you seem to refuse to do. 

    You don't seem to have the basic knowledge and understanding to be an effective object oriented programmer using the MVC UI design pattern and ASP.NET MVC framework.

    You're probability better than this,  you need to step to the plate,  start taking full swings with the bat and stop whiffing all over the place. 

    Sunday, June 28, 2020 2:22 AM
  • User2130491911 posted

    Thank you all the same DA .. your help as well as others is greatly appreciated. 

    Its not that my mind is made up. It is that not everyone has the ability to understand the same way. Just because you write it  does not mean its clear. Your terminology and level of detail was just as difficult to follow as the microsoft documentation / instructions.

    Using words like persistence and models are difficult to follow. I am not a programmer full time. I am not asking anyone here to do my work or anything like that when I ask questions here. I am just trying to understand this technical stuff in the least technical way so that my dumb guy brain can make since of it..

    I think people are trying to help by explaining it the best they can they way they know it. This is your wheelhaus. Your thing. You are the experts. But that guy simplifying it in a way that was practical .vs theoretical without all the big tech words just made some of the mud clearer to my dumb guy brain. So again.. my mine is not made up. It just does not understand fully whats being shares. Sometimes thinks need to be broken down to basic elements. I know none has time for that here as you guys help other the best you can.

    I have lots of training and this idea that I don't know the basics is not true. I dont remember it all as I am not a programmer

    Not sure what you mean by taking the bat... but this not what I do full time. I don;t live and breathe this stuff and only come back to it when a project need a computer program solution. Back when web forms was the rage it was easy and less complicated then all this mvc nonsense.. 

    You could make a drop down list. You could link sql with out twisting the arm of your database off with all the warnings and belligerence of the E form when it comes to database keyfields when using a sql view (see sql views are easy to understand and build)

    I am still confused if you can combine tables and based on some comments here stating that I was doing it wrong but I will just pass on this project.. we have the funds to hire a resource that can knock this out as my week of trying to understand it has made it so I would not get it done in time.. The upside is that I have some understanding of maybe what a view model is, but not really how to use it. 

    I think program has outgrown my skill level ads I made need bow out. this view model thing was a beat down. What a week !

    Thank you people!

    Sunday, June 28, 2020 12:13 PM
  • User1120430333 posted

    Not sure what you mean by taking the bat...

    baseball bat

    Sunday, June 28, 2020 6:02 PM
  • User2130491911 posted

    Yeah I dont play baseball...

    Here is an example of an example that does not make any sense at all and makes this viewmodel thing seem like nonsense... which it is in my personal opinion. Event hough I am passing this project to a 3rd party resource it still would be nice to understand these wacky examples.

    Is it me or does the following example not make sense...?

    The so-called view model, right at the jump this example shows that its blending two tables... but by the end of this example you will see that they are seem to use one.. So why even bother??

    Public class Student
    {
    public int Id {get; set;}
    public string Name {get; set;}
    }  
    Public class Subject
    {
    public int SubjectID {get; set;}
    public string SubjectName {get; set;}
    }
    public class StudentViewModel:Subject
    {
    public int ID {get; set;}
    public string Name {get; set;}
    }
    
    

    So they make a view model from two tables but only uses one table??

    Why would you even do this.. 

    Why isn't the first code block consider a view model when it appears that it is blending two database tables student and subject?

    The explanation that came with this example ignored the fact that it started with two tables.?? 

    I assume this bit of syntax means something 

    public class StudentViewModel:Subject
    

    Sunday, June 28, 2020 8:10 PM
  • User2130491911 posted

    Just messing around with this code as I am curious why this one had grounded me to the ground...

    So I got the application to compile by changing the controller. I used var which as worked for me in the pass...

    The new controller looks like this

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
    
                var LOV_LOCATION = new VM_RMRP_QUESTIONS_Class();
                var RMRP_DB = new RMRP_DB_Entities();
                // VM_RMRP_QUESTIONS_Class LOV_LOCATION = new VM_RMRP_QUESTIONS_Class(); // Setup the data for LOV using view model
                //using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                
                    //LOV_LOCATION.LOCATION_LIST_LOV = RMRP_DB.LOCATION_LOV.ToList <LOCATION_LOV>();
    
                    var DDL = RMRP_DB.LOCATION_LOV.Select(r => new VM_RMRP_QUESTIONS_Class.LOCATION_LOV());
    
                return View(DDL);
    
                    
            }
        }
    }

    my so called view model looks like this now.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class VM_RMRP_QUESTIONS_Class
        {
            //public partial class CONTACT_LOCATION_NUMBER_TBL
            //{
            //    public string LOCATION_ID { get; set; }
            //    public string CONTACT_NUMBER { get; set; }
    
    
    
            //}
    
    
            //public partial class CONTACT_LOCATION_TBL
            //{
            //    public int ID { get; set; }
            //    public string CONTACT_LOCATION { get; set; }
            //}
    
    
            public partial class LOCATION_LOV
            {
                public int ID { get; set; }
                public string Location { get; set; }
     
            }
    
    
            public partial class Eligibility_1
            {
                public int ID { get; set; }
                public string C1P { get; set; }
            }
    
    
            public partial class Eligibility_2
            {
                public int ID { get; set; }
                public string C2P { get; set; }
            }
    
            public partial class Eligibility_3
            {
                public int ID { get; set; }
                public string C3P { get; set; }
            }
    
    
            public partial class Eligibility_4
            {
                public int ID { get; set; }
                public string C4P { get; set; }
            }
    
    
            public partial class Eligibility_5
            {
                public int ID { get; set; }
                public string C5P { get; set; }
            }
    
    
            public partial class Eligibility_6
            {
                public int ID { get; set; }
                public string C6P { get; set; }
            }
    
    
            public partial class Eligibility_7
            {
                public int ID { get; set; }
                public string C7P { get; set; }
            }
    
    
            public partial class Eligibility_8
            {
                public int ID { get; set; }
                public string C8P { get; set; }
            }
    
            [NotMapped]
            public List<LOCATION_LOV> LocDropDownList{ get; set; }
    
            //[NotMapped]
            //public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_HH_NUMBER_LOV { get; set; }
    
    
        }
    }

    I took out some table values because it was first giving some wacky CLR ambiguity error... to I removed those elements from the edmx But now I get this error when I try to run the application... I just keeps getting better.

    System.Data.MetadataException
      HResult=0x80131939
      Message=Schema specified is not valid. Errors: 
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'LOCATION_LOV'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.LOCATION_LOV', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+LOCATION_LOV'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_1'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_1', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_1'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_2'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_2', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_2'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_3'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_3', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_3'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_4'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_4', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_4'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_5'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_5', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_5'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_6'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_6', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_6'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_7'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_7', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_7'.
    The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'Eligibility_8'. Previously found CLR type 'RMRP_SELF_ASSESSMENT.Eligibility_8', newly found CLR type 'RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class+Eligibility_8'.
      Source=<Cannot evaluate the exception source>
      StackTrace:
    <Cannot evaluate the exception stack trace>
    

    What is that???

    This is nutty... is my visual studio broken???

    Monday, June 29, 2020 12:01 AM
  • User1120430333 posted

    Why would you even do this..

    You're reregurgitating junk code and you need to stop.

    Monday, June 29, 2020 12:33 AM
  • User1120430333 posted

    What is that???
    This is nutty... is my visual studio broken???

    I gave you a valid VM to work with that is viable. Why do you keep regurgitating the same code over and over?

    Monday, June 29, 2020 12:39 AM
  • User2130491911 posted

    Just re-reading this... this does not make sense to me on so many levels...

    First this is only one table from a database that has many tables.

    Next. Why is it you have the ID required? Th

    Why would I need to type in the ID if I am trying to just make a list from a view model that I thought I would need to have all the tables there so that I can make other drop down list from the data..

    This is very confusing 

    They project that I am no longer part of need to have two drop down list. There was no data entry. Basically the user selects a value from each list. 

    That value would be sent to the controller and processed then return a result to the screen.

    I am not seeing how I would have made use of this for a program such as that.

    I mean is it really this difficult to make a dropdown list from a view model?

    Should I just have use the auto generated classes and put the list selectlistitem thing in there... I would have never needed to refresh the demx from data base so the class would not have been overwritten.

    Just look to do a postmortem of what went wrong here..

    Monday, June 29, 2020 12:41 AM
  • User2130491911 posted

    I am not offended that your called my source code junk but man that was rude...  Geez.

    I am not doing that... the source code was changed... I am just trying to get what I have written to work so its very different and I am getting very different results.

    I am trying to apply the stuff from all of the post but Its not going well ... I was just showing my work. Maybe someone out here on the net can help.

    But I am not spamming your site. 

    I have been working on this all week and all day to day for over 8 hours trying all the different things people have shared.

    Just trying to make it work.

    Do you know of another site that may be more willing to help? THey are way too mean on that stack overflow...are there any other helpful communities you can recommend they may be able to help some one understand view models and dropdownlist using viewmodels

    Monday, June 29, 2020 12:45 AM
  • User1120430333 posted

    Here is one VM for two dropdownlists. You can rename everything in it anything you want. You can have two different tables that will populate the dropdownlist populating the SelectListITem qnd loading them into their List<SelectListItem> collection. You send the Dropdownlist_VM  and send it into a view that is going to use one or both of the dropdownlists.. You can make Dropdownlist_VM be an object in another VM and send both VM(s) into a view. 

    https://nimblegecko.com/using-simple-drop-down-lists-in-ASP-NET-MVC/

    http://dotnetmentors.com/mvc/how-to-bind-dropdownlist-in-asp-net-mvc-application.aspx

    The model in the 1st article is really a VM. 

    But what you should do is abandon the code to do a Linq query that you have. You can change the code and make it comeback with a list of database table objects, go into a foreach loop, create a new SelectListItem, populate it from the database table object and load the SelectListItem into its appropriate list.

    If you can't figure it out from this point, then I don't know what to tell you.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
       public class DropDownList_VM
       {
           [Required(ErrorMessage = "LOCATION_LOV is required")]
           public LOCATION_LOV_ID { get; set; }
    
           public List<SelectListItem> LOCATION_LOVS { get; set; } = new List<SelectListItem>();
    
           [Required(ErrorMessage = "Other ID is required")]
           public Other_ID { get; set; }
    
           public List<SelectListItem> OtherList { get; set; } new List<SelectListItem>(); 
       }
    }

    Monday, June 29, 2020 3:02 AM
  • User2130491911 posted

    I guess based on reading the links view models can only be used when hardcoding dropdown list. vs being used from an actual database.  I am guessing that they see a database as data in side the program and not outside of it which now makes it clear why you have the view model stating it was a required field.

    That was throwing me for a loop.. (no pun intended)  In the project that I abandon it had about 200 hundred entries. But I could have type them in no problem. So am I correct in thinking if I want to use a view model I have to type in the values  inside of the program first then bind that to the dorpdown list  but first I would need to build some type of data entry form first so that I have a way to populate that list first since the view model requires the ID and description fields?

    If that's the case I get that now...  I was thinking that a view models would allow you to pull from an actual database vs having a local one inside of the actual program. I guess my approach was all wrong lol. Now it also makes sense what the other user was stating when they said a view model is not just for a database and now its clear why my attempt was not "seeing" my data because it was loooking for a hard coded list and not an actual relational database from the server.

    Now I know.  Thanks for this as it should give me a base to work with  know that view models require things to be more manual and hard coded..

    I appreciate the patience... sorry It took me so long to get this!

    Monday, June 29, 2020 11:49 AM
  • User1120430333 posted

    I guess based on reading the links view models can only be used when hardcoding dropdown list. vs being used from an actual database.

    Of course there are various HTML controls like  a Label, TextBox, TextArea and other such controls that properties of a VM object works with.

    which now makes it clear why you have the view model stating it was a required field.

    The required field is to hold the ID of the SelectListIem with ID populated to the 'value' property for the SelectListItem .  If the oser never makes a section fro the dropdownlist, the an error message is shown to the user. 

    Populating a VM can come form database data, like a Controller is doing an edit of exiting data record in a database. Code populates the VM from the database object,  and the VM is sent into the view. The user makes changes to data because a control is liked to a VM property. The user saves the data with all the data the user enter or selected on controls tied to properties of the VM. Code  populates VM  data back to a database model object and EF saves/persist  the data to the database.;   

    Monday, June 29, 2020 1:17 PM
  • User2130491911 posted

    Hi Da924 or anyone that may know ... I have a follow up question...

    I thinking about what  wrote and I think you stated that  that you should not make a view model using the a copy paste of the contents from the automatically generated code for the database table.

    This seems odd. If my actual database field and table name are what they are...

    Why would they not be the same in the view model? And if the should not be the same... what should the be called?

    Changing their field names seems like you would add so much complexity and confusion.

     

    Example this is Auto Generated code from the EDMX file

    // <auto-generated>
    // This code was generated from a template.
    //
    // Manual changes to this file may cause unexpected behavior in your application.
    // Manual changes to this file will be overwritten if the code is regenerated.
    // </auto-generated>
    //------
    namespace RMRP_SELF_ASSESSMENT
    using System;
    using System.Collections.Generic;
    {
    public partial class A_TABLE_FROM_SQLDB_NAMED_A { public int FIELD1 { get; set; } public string FIELD2 { get; set; } }
    }

    Why would the view model not be the same??

    namespace NEW_APPLICATION.ViewModels
    {
        public class APPLICATION_DATA_VIEWMODEL_Class
        {
    using System;
    using System.Collections.Generic;

    public partial class A_TABLE_FROM_SQLDB_NAMED_A
    {
    public int FIELD1 { get; set; }
    public string FIELD2 { get; set; } } }
    }

    I guess what I don't get if if this view model is just a mask for the database table how does the computer know that I want this viewmodel to reference this database table?

    Thanks

    Monday, June 29, 2020 9:09 PM
  • User1120430333 posted

    I guess what I don't get if if this view model is just a mask for the database table how does the computer know that I want this viewmodel to reference this database table?

    Part of your problem is that you have been brainwashed by the cheesecake teaching of ASP.NET MVC tutorials,  and you're not a seasoned software developer that has seen other UI patterns implemented  in ASP.NET Web UI and Windows desktop UI solutions.  

    It may very well be that the UI view and VM  may originate from on a database table. But that doesn't mean that you take the EF Model that the EF EDMX generates and solely think that everything will be  static in the cloned VM and nothing will change at the UI where a HTML control is introduced and its data  property on the VM has nothing to do with a database table. But the VM posted back to the controller used by the  introduced HTML: control its VM  property data  is used in some kind of decision making process. There are many reasons as to why properties on a VM do not originate from a database. And that's where one draws the line and separate where  a VM is solely for working with the UI view that may or may not have properties on a VM  that lead back to a database table column.

    https://deviq.com/kinds-of-models/

    <copied>

    View Model
    Many developers are familiar with the concept of a ViewModel, especially those who have used application frameworks that use the Model-View-ViewModel pattern. In an MVC web application, a ViewModel is a type that includes just the data a View requires for display (and perhaps sending back to the server). ViewModel types can also simplify model binding in ASP.NET MVC. ViewModel types are generally just data containers; any logic they may have should be specific to helping the View render data. There may be many similar ViewModel types, each tailored to the needs of a particular View.

    <end>

    Seperation of concerns, speration of concerns and  repeat it with me  --  seperation of concerns.

     https://en.wikipedia.org/wiki/Separation_of_concerns

    The name of the VM and the property names are not verbatim as seen on a database table. Can you have a little originality?

    Tuesday, June 30, 2020 1:25 AM
  • User-474980206 posted

    there is nothing wrong with using the same property names, but using the same class names for the view mode is confusing. again be c# is strong typed, name two classes the same does not make them interchangable.

    I recommend adding common suffix to the end of the model class models so you don't get confused.

    using System;
    using System.Collections.Generic;
    
    namespace NEW_APPLICATION.ViewModels
    {
        public class APPLICATION_DATA_VIEWMODEL_Class
        {
    
            public partial class A_TABLE_FROM_SQLDB_NAMED_A_Model
            { 
               public int FIELD1 { get; set; }  
               public string FIELD2 { get; set; } }
            }
        }
    }
    

    Tuesday, June 30, 2020 1:58 AM
  • User2130491911 posted

    Ok so you are advocating and not helping...DA so again thanks but you are not helping. You are so far above my head that you may be in orbit. I keep trying to relay to ou I have NO idea what you are trying to share. Its too high level.

    I am not trying be a season developer mate.. I am trying to understand a pretty difficult (to me) concept. You are the very first person that I have ever come across that has stated that tutorials and microsoft documentation are cheesecake. most people say use that stuff to learn. Its not about originality mate. Its about finding a way to understand the difficult concept.

     I  am not sure what you mean but I assume what your insult is conveying is learning by example is not good. and we all need to be as smart as you, Sorry mate. But you are advocating at the wrong chap Ol'chum. Nothing personal but I no longer need your feedback as you are too advance for this cheese cake eater (cheese cake is gross by the way). Forgive me for asking you something directly, 

    But yeah you are not helping. So if your goal is to advocate a design pattern please take that some where else. You have single-handedly confused me to the point I truly  realise I don't need to try use view models EVER as they are not a tool for programming but a soap box for pushing a design preference. Clearly I have wasted my time and every one elses thinking this would be an easy explanation and a useful data structure.

    I leave this thread knowing less then when I started it, Thanks a lot... not your fault its my own thinking view models were useful and worth the hours spent trying to understand them. Mods please lock this pointless thread.. It has now lost its way.

    Tuesday, June 30, 2020 2:15 AM
  • User2130491911 posted

    Ah.. so it was the way I had it named... ok I will give that a true. thank you for that.

    Tuesday, June 30, 2020 2:17 AM
  • User1120430333 posted
    Some people are just not meant to be a software developer. Maybe you're better off being in a business analyst role. Like Clint Eastwood said in a movie. A man has got to know his imitations.
    Tuesday, June 30, 2020 5:43 AM
  • User2130491911 posted

    No need for personal attacks or rude comments mate.  

    Tuesday, June 30, 2020 10:53 AM
  • User1120430333 posted
    I am not personally attacking anyone or being rude. You flew off the handle with a bunch of gibberish about what you were not going to do, because you didn't get the response you wanted. I gave you information on things and why to use them. If you can't accept information that's on you. It's obvious that you don't have the skillset to be an effective .NET software developer. You should look into another position and move out of software development, IMHO. There no insult. You're just being told the truth.
    Tuesday, June 30, 2020 11:50 AM
  • User2130491911 posted

    Ok thanks.  

    There was no response I wanted... I wanted to understand the response mate.

    Your Response was a bit too technical.  

    So all is well. Lets be buddies again! Take care mate.

    Tuesday, June 30, 2020 1:43 PM
  • User2130491911 posted

    Hi Mgebhard,,

    I am going through each of these examples and trying to extract some understanding and I am not understanding a few things you listed here.

    You wrote

        public class ExampleViewModel
        {
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_LOCATION_NUMBER_TBLs { get; set; }
        }
    
        public class CONTACT_LOCATION_NUMBER_TBL
        {
            public string LOCATION_ID { get; set; }
            public string CONTACT_NUMBER { get; set; }
        }

    I find this listing confusing 

        public class ExampleViewModel
        {
            public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_LOCATION_NUMBER_TBLs { get; set; }
        }

    Are you writing that that one class is a view model? And why is the table name duplicated here? I see the smalls... what does that represent I mean I know its the name but what does this line of source represent?

    public List<CONTACT_LOCATION_NUMBER_TBL> CONTACT_LOCATION_NUMBER_TBLs { get; set; }

    I am thinking I am not confused about what get set means. but I look that up later.

    I am not finding any guidance on that. 

    So if I wanted all my tables to be part of the view model I would have to duplicate the name with a small letter s?

    Sorry but I am beyond lost.
     

    Tuesday, June 30, 2020 6:04 PM
  • User-474980206 posted

    Our confusion is that we assume a poster to this forums has a beginners understanding of C#, not advanced, but knows basic syntax, and some of the common features of a strongly typed languages. 

    to C# a view model is just a class and an entity model is just a class, its the usage that matters.

    for example, beef is beef. but put it in a mincemeat pie its dessert, and put it in a stew its dinner.

     

    Tuesday, June 30, 2020 6:30 PM
  • User475983607 posted

    AppDev01

    Are you writing that that one class is a view model?

    Yes.  A View Model is a single class. 

    AppDev01

    And why is the table name duplicated here? I see the smalls... what does that represent I mean I know its the name but what does this line of source represent?

    The "s" means plural.  A more standard naming conversion as shown below should help clarify.  Notice the pattern is the same as yours only the class and property names have changed.

    public class ColorsViewModel
    {
        public List<Color> Colors { get; set; }
    }
    
    public class Color
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    AppDev01

    So if I wanted all my tables to be part of the view model I would have to duplicate the name with a small letter s?

    It is just a naming convention.  I put an "s" at the end of the property names that are collection types.  This helps to identify single items and collections; color and colors.  There is no reason to look any deeper.  There is not secret meaning.  It's just a property name.

    Tuesday, June 30, 2020 7:09 PM
  • User2130491911 posted

    Bruce you keep pushing this strongly typed nonsense, mate no one cares about that. To be honest I have no idea what you are talking about... I use var all over the shoppe. It keeps me out of trouble and the program works. It may not be what you like but I do wish you would stop with this snark. 

    I understand C pretty well. Not everything about C but what I need to know to do the work I need to do. Here I am trying to expand what I know because I have had to work around this gap on view models... not because I don't understand the basics.. I don;t understand view models. So much so that the confusion has me at place where I think I really do need to continue to avoid the.

    Knowing the c has nothing to do what asking questions about the syntax.  To you this is basic to me its a mess. So I have to ask foundational questions which is how I learn.

    So for clarity... You are not confused... you are just being rude. I am the one confused so I am asking very basic questions so that I may at least trying to understand what Is going on here.

    My gut feeling is that this concept will elude me as it is way to abstract for my brain. I doubt I will ever get view models to work. I wish there was a good step by step video

    of someone doing this with no gaps or assumptions and using a database and not a hard coded list. Maybe seeing that it will make sense. 

    So if you know of any good videos let me know if you don't mind

    Wednesday, July 1, 2020 2:53 PM
  • User1120430333 posted

    you keep pushing this strongly typed nonsense, mate no one cares about that. To be honest I have no idea what you are talking about... I use var all over the shoppe. It keeps me out of trouble and the program works. It may not be what you like but I do wish you would stop with this snark.

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var

    <copied>

    Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit "type" var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:3

    <end>

    AppDev01, you are so far out of line, it's unbelievable,  and you don't know what you're talking about. 

    Maybe, you should look up terminology being talked about instead of flying off the handle with nonsense.  Like lookup what is a type? What does strong typed even mean?

    Wednesday, July 1, 2020 3:38 PM
  • User2130491911 posted

    Thank you mgebhard,

    So in your example you have

    public class ColorsViewModel
    {
        public List<Color> Colors { get; set; }
    }
    
    public class Color
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    But what if my SQL_SERVER database has 4 tables

    COLOUR_TBL

    SHAPES_TBL

    COLOUR_SHAPES_USER_SELECTION_STORAGE_TBL

    So the way the application would work is that the user would have a 2 drop downlist One for Colour Selection and the Other for Shapes Selections

    The database table for COLOUR_TBL and SHAPES_TBL would have the colours styles  and shape types  and the selection table would store the user combinations that they select from a form page, so would the sample below be a  viable view model class:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    
    namespace COLOUR_SHAPE_SELECTOR_CLASS.ViewModels;
    
    public class VIEW_MODEL_CLASS_FOR_COLOUR_SHAPE_SELECTOR
    {
    
             public partial class SHAPES_TBL
            {
                public string SHAPE_ID { get; set; }
                public string SHAPE_DESC { get; set; }
    
            }
    

    public class SHAPES_TABLE_ViewModel { public List<SHAPES_TBL> SHAPES_LOV { get; set; } }

    public partial class COLOUR_TBL { public string COLOUR_ID { get; set; } public string COLOUR_DESC { get; set; } }
    //THIS IS THE VIEW MODEL FOR THE DROP DOWN LIST OF VALUES?
    //SO UNLIKE WHAT WAS SHOWN BEFORE I DON'T NEED TO HAVE
    // ID and Desc fields? OR Do I need to have the table Fields??
    public class COLOURS_TABLE_ViewModel { public List<COLOUR_TBL> COLOURS_LOV { get; set; } }


    public partial class COLOUR_SHAPES_USER_SELECTION_STORAGE_TBL { public string STORED_COLOUR_ID { get; set; } public string STORED_COLOUR_DESC { get; set; } public string STORED_SHAPE_ID { get; set; } public string STORED_SHAPE_DESC { get; set; } } //LIST For LOV Drop Down public partial class COLOUR_TBLs { public string COLOUR_ID { get; set; } public string COLOUR_DESC { get; set; } }
    //LIST For LOV Drop Down public partial class SHAPES_TBLs { public string SHAPE_ID { get; set; } public string SHAPE_DESC { get; set; } } }

    So in other suggestions to this topic people had the ID and Description fields as part of the element for the drop down list.

    In you sample you did not. Do I assume I don't need the ID field for the drop down list when setting it up in the view model?

     

    Wednesday, July 1, 2020 4:33 PM
  • User475983607 posted

    AppDev01

    So in other suggestions to this topic people had the ID and Description fields as part of the element for the drop down list.

    In you sample you did not. Do I assume I don't need the ID field for the drop down list when setting it up in the view model?

    Well, no.  It seems like you are searching for a deeper meaning when the concept is very simple.

    If you are designing an input form and that form has a select element then the view model needs a property name that matches the input element name.  Otherwise, the model binder will not populate the view model property with the user's selection.  This is a fundamental MVC concept covered in all beginning level tutorials.  

    It is up to you to design models that meets your user interface design requirements. 

    Wednesday, July 1, 2020 5:31 PM
  • User2130491911 posted

    Ok.. yeah I think I have gotten so many different answers on this that the View model thing is truly too hard for me to grasp.

    All of the tutorials seem to hard code the list which is not what I was trying to do and not helpful as they don't show how one would use a database.

    I thought my last attempt was spot on though. But I am guessing this was not the case 

    Finally are you saying you only need the view model for data entry and that they are not needed for drop downlist where you just want to take records from a database and display them as a list?

    Thanks for the feedback.

    Wednesday, July 1, 2020 5:56 PM
  • User2130491911 posted

     Ok I found this example... about it goes off the rails... where is the view models? They state there will be a view model but they don't show it.

    and thankfully they define what is meant by the word bind that some of you use... that is just another way for saying populating... that is good to know.

    https://www.aspsnippets.com/Articles/Populate-Bind-DropDownList-from-ViewModel-in-ASPNet-MVC.aspx

    The write up states the following : 

    <div>In this article I will explain with an example, how to bind (populate) DropDownList from ViewModel in ASP.Net MVC Razor.</div> <div>The DropDownList will be populated from database using Model class and the Html.DropDownListFor Helper method.</div>

    No where else in this example does the user mention the word view model... (sigh : ( )

    But in the example they only show the data mapping from the database and not a view model...  So did he set something special so that the default database would make the selectlistitem in an auto generated way?

    I see that this is not using EF ... does EF have a setting or something that I need to set? Again where in the world is the view model he promised? 

    I only see this model which would be created by the edmx files correct if using edmx and ef correct?

    Somethings these examples can be so frustrating. 

    Here is the model... why would he show that and not the view model???

    This will be my last question on this topic. Sorry so many questions but I just don't get why I can't find a decent example of this concept that is clear.

    Model
    The following Model class has three properties Fruits, FruitId and Quantity.
    The Fruits property is a Generic list of SelectListItem class which is an in-built ASP.Net MVC class. It has all the properties needed for populating a DropDownList.
    
    public class FruitModel { public List<SelectListItem> Fruits { get; set; } public int? FruitId { get; set; } public int? Quantity { get; set; } }

    Pulling up the old source code from the abandon project... it looks like my issue could be some where related to this stuff here.

          public List<LOCATION_LOV> LocDropDownList { get; set; }

    That give me this error Here:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.LOCATION_LOV>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.VM_RMRP_QUESTIONS_Class.LOCATION_LOV>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	23	Active
    

    Should I not use the table I am trying to  make as a list for the drop down?

       VM_RMRP_QUESTIONS_Class vM_RMRP_QUESTIONS_Class = new VM_RMRP_QUESTIONS_Class();
                //RMRP_SELF_ASSESSMENT.LOCATION_LOV LOV_LOCATION = new RMRP_SELF_ASSESSMENT.LOCATION_LOV(); // Setup the data for LOV using view model
                using (RMRP_DB_Entities RMRP_DB = new RMRP_DB_Entities())
                {
                   vM_RMRP_QUESTIONS_Class.LocDropDownList = RMRP_DB.LOCATION_LOV.ToList();
                }
    
                    return View(vM_RMRP_QUESTIONS_Class);

    This is the only error I get so I may be close to resolution?

    Wednesday, July 1, 2020 6:25 PM
  • User475983607 posted

    You continue to search for some super secret hidden meaning when the definition is all you need.  A view model is an term given in to a class passed from a controller to a view and a view to a controller.  The properties that make up the class are determined by the user interface design requirements.  That's it...

    AppDev01

    Here is the model... why would he show that and not the view model???

    The example you provided is a view model.  It has a select list to populate a select element (controller -> view), and Id to get the selected option from the user (post -> controller), and also a quantity input.  Why do you think it is not a view model?

    Wednesday, July 1, 2020 7:40 PM
  • User2130491911 posted

    Not sure that I don't think it's a view model ... but they did not call it a view model so it seems like it would not be a view model. When they wrote the example, they stated they were going to use a viewmodel yet the source code shows the word model. So that is the source of confusion.

    I am not looking for a secrect meaning just a simple basic meaning as they are not used for what I thought.

    I should just change the edmx models and try to add a selectlist to it vs trying to figure out the view model.

    I can make a text file in the program that has the changes to it so if I ever updated the EDMX I can just copy an paste the information back into the auto generated cs files.

    At that point the program already sees the files and I won't get that silly error that It can convert some to something implicitly which makes no sense to me at it seems people get that error alot when trying to use view models. 

    My example I am using using EDMX it already has something called model.. so I would have have what he has listed twice which is very confusing. I guess this users example is not compataible with the example I have as I guess I need to find some one that is using edmx and view models and dropdown list to see what it is they do to make it all work and why they bother with view models in the first place.

    It's examples like these that really mess you up. 

    When you write user interface design requirements.. I am not sure what you mean. What other properties ? Are you meaning validation and field names? 

    Would a user list all their fields they need in one View model? even it they spanned multiple database tables? 

    Seems like the better approach would be to just mod the wizard generated files and just make back ups and replace them should you updated the edmx as stated before.

    Who knows...

    I will re-read it again to see if I can make heads or tails out of it. Thanks!

    Thursday, July 2, 2020 3:19 PM
  • User475983607 posted

    My example I am using using EDMX it already has something called model.. so I would have have what he has listed twice which is very confusing. I guess this users example is not compataible with the example I have as I guess I need to find some one that is using edmx and view models and dropdown list to see what it is they do to make it all work and why they bother with view models in the first place.

    EDMX models are part of entity framework which has nothing to do with MVC models,  Sadly, you continue to mix the two frameworks.  

    When you write user interface design requirements.. I am not sure what you mean. What other properties ? Are you meaning validation and field names?

    Exactly, user input validation is part of the user interface design.   Typically, the end users drive the UI design.  It's your job as a developer to craft a UI that meets the users expectations.  

    Anyway, the problem you are facing is not view models.  A view model is just a class.  You are struggling with C# language fundamentals and the programming problems MVC and EF solve. 

    Thursday, July 2, 2020 7:02 PM
  • User2130491911 posted

    Hi Mgebhard

    Okay so I started over and reconfigured the folder structure of the application and reduced the number of tables for this view model and still coming up with the same error. Could it be a bug in my visual studio??

    I still get this error which is not making any sense to me as I am following a tutorial almost word for I am just using my database.

    When I use

            public List<COUNTY_LOCATION_TBL> CountyLocationDropDownList { get; set; }

    I get this error :

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.Models.COUNTY_LOCATION_TBL>' to 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.ViewModels.RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS.COUNTY_LOCATION_TBL>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	21	Active
    

    And when I change the Item to select list I get the is error

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.Models.COUNTY_LOCATION_TBL>' to 'System.Collections.Generic.List<System.Web.Mvc.SelectList>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	21	Active
    

    When I use this Line:

            public List<SelectList> CountyLocationDropDownList { get; set; }

    I Get This Error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.Models.COUNTY_LOCATION_TBL>' to 'System.Collections.Generic.List<System.Web.Mvc.SelectList>'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	21	Active
    

    Here is the clean up and paired down source code: Any ideas would be appreciated. In this case I left one setup with selectlist like I see in some example and in the other I left the table name like I see in some examples. I am not sure what is missing here.

    The over all usage that I am trying to achieve is that I have this so called view model setup for all the drop down list I need for the application's user interface. In this case I need 2 of them, they are called 

    CountyLocationDropDownList and ContactLocationDownList 

    I tried using the following

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.Models;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS
        {
    
            public List<SelectList> CountyLocationDropDownList { get; set; }
    
            public partial class CONTACT_LOCATION_TBL       {
                public int ID { get; set; }
                public string Location { get; set; }            
            }
    
            public List<CONTACT_LOCATION_NUMBER_TBL> ContactLocationDownList { get; set; }
    
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
            }
    
        }
    }

    And again the controller has been clean up 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.Models;
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
    
                RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
                using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities()) 
                {
                    RMRP_DDL_VM.CountyLocationDropDownList = RMRP_DB.COUNTY_LOCATION_TBL.ToList();
                }
    
                    return View(RMRP_DDL_VM);
            }
        }
    }

    The view model is in a folder called Viewmodels and the Edmx files are in a folder called model.

    I don't understand what is going wrong here.

    The Error indicator line is under the part in bold underline

    RMRP_DDL_VM.CountyLocationDropDownList = RMRP_DB.COUNTY_LOCATION_TBL.ToList();

    Do I have this part here setup wrong?

    Thursday, July 2, 2020 8:25 PM
  • User1120430333 posted

    Do I have this part here setup wrong?

    Yeah it's wrong. It should be SelectListItem NOT SelectList.

    public List<SelectList> CountyLocationDropDownList { get; set; }  // it is wrong.

    https://docs.microsoft.com/ko-kr/dotnet/api/system.web.mvc.selectlistitem?view=aspnet-mvc-5.2

    https://odetocode.com/blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

    A class is the blueprint for an object that defines its methods/behavior, properties and private variables.

    How can a  the below class ever be a SelectListItem class in the link?

    public partial class CONTACT_LOCATION_NUMBER_TBL
    {
       public int ID { get; set; }
       public string CONTACT_LOCATION { get; set; }
    }

    https://docs.huihoo.com/dotnet/aspnet/api/1.0.0/autoapi/Microsoft/AspNetCore/Mvc/Rendering/SelectListItem/index.html

     using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities()) 
                {
                    RMRP_DDL_VM.CountyLocationDropDownList = RMRP_DB.COUNTY_LOCATION_TBL.ToList();  //IT IS WRONG THE ONE CAN't BE = OR BETHE OTHER
                }

    So of course, you're going to get the Cannot implicitly convert type on the above statement, becuase COUNTY_LOCATION_TBL class/type can never be a SelctListItem That the List is strong typed to be, becase  the two classes that define each object are different.

    You talked about var and how it saved you.

    using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities()) 
    {
    var retults = RMRP_DB.COUNTY_LOCATION_TBL.ToList();

    RMRP_DDL_VM.CountyLocationDropDownList drplist = new List<SelectListItem>();

    foreach(var item in results)
    {

    var sli = new Sele3ctListItem();
    sli.value = item.ID;
    sli.text = item.CONTACT_LOCATION'
    drplist.Add(sli);
    }

    Take note on this: If you had a object named AppDev01 that's defined in namespace zzzz or zzzz.AppDev01,  and you had the same AppDev01 in namespace kkkk or kkkk.AppDev01, then you can't do the below either.

    zzzz.AppDev01 = kkkk.AppDev01 //.NET will not allow the casting of an object across two different namespaces.

    Friday, July 3, 2020 4:11 PM
  • User2130491911 posted

    Ok I will give these fixes a try. I was following someone message board example and it may have been pseudo code so they left some things out.

    On this point.. I am not clear what you are trying to convey here.

    Take note on this: If you had a object named AppDev01 that's defined in namespace zzzz or zzzz.AppDev01,  and you had the same AppDev01 in namespace kkkk or kkkk.AppDev01, then you can't do the below either.
    
    zzzz.AppDev01 = kkkk.AppDev01 //.NET will not allow the casting of an object across two different namespaces.

    So in my example above is that what I am doing? This casting as you call it across name spaces.

    Is there any way to define this situation in a non technical way.

    What loses me is how are you to tell the drop down list what table to use?

    So for me it would seem you would need to some how let the computer know that you need table a to make up the drop down list.

    YOu asked how can this 

    public partial class CONTACT_LOCATION_NUMBER_TBL
    {

    public List<CONTACT_LOCATION_NUMBER_TBL> CountyLocationDropDownList { get; set; }
    To me the above makes sense... its like hey computer take this database table you know about. Do you magic at compile and turn this database table
    into a list.

    Then when in the controller you do your thing something.CountyLocationDropDownList blah blah...
    To me that seems like it should work...

    But clearly view models dont work that way
    public int ID { get; set; } public string CONTACT_LOCATION { get; set; } }

    be a select list... I don't see why not... Its already a list in the database.

    And just about every example I see has people adding either List or selectlist or selectlist item right underneath or above with in the tables partial class definition

    so you are asking me a question you need to ask microsoft and or the people making this tutorials on this so called view model craziness..because I cant follow its a bit too high level for me. I think if I can get just one example to work I can mimic it forever and have that data structure as a tool I can follow and use as a code sample for when I get assign an application.

    So to answer your question I truly do not know why it can't be.

    You wrote that  two classes that define each object are different. So I can I make these the same so they can work? I mean the help on this error seems scatter shot.

    And a web search does not really give clear direction on fixing it.

    I know you are for strong type stuffs...and that's cool but can you put on you not so strong type hat  and maybe share some clues that would allow me at my current understanding to fix this with issue with in my scope  of understanding?

    It may not be possible and it may never work... but I thought I was close this time. Thanks

    Friday, July 3, 2020 5:16 PM
  • User1120430333 posted

    So in my example above is that what I am doing? This casting as you call it across name spaces.

    No that's not the problem you are having. You have been given dropdownlist tutorials that clearly defines the usage of a SelectListItem class with it being a key element in working with a dropdownlist. The definition of the List the dropdownlist uses is strong typed to SelectListItem object. It means that any object that you try to load into the List must be a SelectListItem. It can't be another type of object not your database objects nothing but a SelectListItem can be loaded into the List, becuase the List is strong typed to SelectListItem. Otherwise, the wrong type of object  like your database table object is going to lead to an exception to be thrown, becuase you are trying to load a wrong type of object into the List due to SelectListItem is what .NET and the List expects.

    If the List is defined for a Bus object, then it's not accepting a plane, boat, car or any other object but a bus object. It had better be a bus object you're loading into the List, which is a strong type List for Bus.   

    so you are asking me a question you need to ask microsoft and or the people making this tutorials on this so called view model craziness

    If I put your problem before my 5 year old nephew and give him the push that you have been given with example code, which I have done, he would have no problem doing it. That's how simple it is.

    It may not be possible and it may never work... but I thought I was close this time. Thanks

    You flat-out have been shown what to do. I just gave you the code. You keep doing a deep dive  to the loop in your mind, trying to do what you think should be done, time and time again you have rolled the dice and you have crapped-out.

    Why you can't follow the examples of code that I and others have given you is a mystery?

    Friday, July 3, 2020 6:14 PM
  • User475983607 posted

    AppDev01

    And just about every example I see has people adding either List or selectlist or selectlist item right underneath or above with in the tables partial class definition

    I'm not sure what you mean by underneath.  The SelectList and the List<SelectListItems> are both .NET classes designed for populating HTML list helpers like the Html.DropDownList and Html.DropDownListFor<T>.  Typically, the SelectList and List<SelectListItems> are populated from a IEnumerable<T> resulting from a LINQ query.   It is very common for a view model to contain a SelectList or List<SelectListItems> similar to the example you provided above.  

    Sadly, the type cast error you are complaining about has been explained to you many times.  The concept is  very simple.  The two highlighted types are not not the same.  You cannot assign one type to the other.  This is a rule.  Now that you know the rule stop making this mistake or at least recognize the mistake and fix your code.

    Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<RMRP_SELF_ASSESSMENT.Models.COUNTY_LOCATION_TBL>' to 'System.Collections.Generic.List<System.Web.Mvc.SelectList>' RMRP_SELF_ASSESSMENT C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs 21 Active

    Fortunately, the SelectList has a constructor overload that accepts any IEnunerable<T> along with the name of the text and values fields.  By the way, in C# a constructor populates a type.  Anyway, this is why you see the SelectList and the List<SelectListItems> type in examples.  

    SelectList options = new SelectList(db.CONTACT_LOCATION_NUMBER_TBL, "LOCATION_ID", "CONTACT_NUMBER");

     In a nut shell, you're taking a result set and converting the results set into another type designed for rendering HTML.  We call this a view model. 

    AppDev01

    I know you are for strong type stuffs...and that's cool but can you put on you not so strong type hat  and maybe share some clues that would allow me at my current understanding to fix this with issue with in my scope  of understanding?

    In my opinion, a lot of the problems you face are due to copying code from the internet in hopes the code will magically function as expected.   That's called cargo cult programming.  <--READ the link.

    In your case, when the code does not work as expected you come up with very imaginative but false correlations.   This stops you from fixing the holes in your understanding because you filled the holes with misinformation.   It all comes down to not understanding C#, MVC, and EF.

    Friday, July 3, 2020 6:55 PM
  • User2130491911 posted

    First have your Nephew email me if he can understand this... I'll zip up my example and send it you to send to him. 

    As far as following the example I have been. Where they are falling short is that they are using hard coded list and my list comes from a database.

    Where they fall short... is that I am using a view model and from what I can tell they are not.

    My problem is not how to do a drop down list, My issue is how to do a combination of 3 things.

    Using a database to make a drop list via a view model. This may not be something that is necessary because  because a view model would not do anything

    meaningful to that list data from the edmx class. But it would be nice to get that combo to work.

    So its no mystery... the tutorials have left me where because I am not able to join all 3 concepts into one.

    Monday, July 6, 2020 1:36 PM
  • User2130491911 posted

    So you stated fix my error... I don't think I know how... I am literally back where I started ... with this error. I get what you all are saying that a Bus can't be a plane in the programming world... but I am not sure how to fix that incorrect assignment.

    One persons tells me their nephew can fix it. No help there because they did not leave any contact info. 

    You sent me a link to a guy that tells me that I am stupid for learning how humans learn... sadly no help there as I have stated that when I don't know something I look to examples and try what I see. And when it does not work I try something else with the hope of not only to get things to work but to then develop an understanding why it works so it can be added to the toolbox for later.

    I have shown example after example where I have tried to fix it based on my ability and based on reading the information provided. 

    Make no mistake I admit I don't know all there is to know... but I am truly stomped. And no that has help can seem to help me with in the scope of my actual example.

    Now mgebhard I see you posed this : 

    SelectList options = new SelectList(db.CONTACT_LOCATION_NUMBER_TBL, "LOCATION_ID", "CONTACT_NUMBER");

    Is that the fix I need  I did not have any word options in my code but I can see from the example above that you are making a list out of the two fields

    But is this for the view model? Or for the controller? IS the view model part of what I have written correct? Which is my main question...

    Because the code you left looks like it should go into the controller by I just want to be sure as I an so confused that I am not sure what goes where based on the volumes of reading in this months long quest 

    Thanks.

    Update I get this to finally compile thanks for the clue.. Now I can't get it to populate the drop down so now I am looking for solutions for that.

    This compiles:

            public ActionResult Question_Intake()
            {
    
                RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
                using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities()) 
                {
                   // RMRP_DDL_VM.CountyLocationDropDownList = RMRP_DB.COUNTY_LOCATION_TBL.ToList();
                    SelectList DDL_COUNTY_LOV = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "LOCATION");
                }
    
                    return View(RMRP_DDL_VM);
            }

    It leads me to this question about the view model.

    Should this line : public List<SelectList> CountyLocationDropDownList { get; set; } go above the table definition or should be contained in the table definition 

    Outside

            public List<SelectList> CountyLocationDropDownList { get; set; }
    
            public partial class COUNTY_LOCATION_TBL
            {
                public int ID { get; set; }
                public string LOCATION { get; set; }
    
                
            }

    Or Inside 

            public partial class COUNTY_LOCATION_TBL
            {
                public int ID { get; set; }
                public string LOCATION { get; set; }
    
                public List<SelectList> CountyLocationDropDownList { get; set; }
    
                
            }

     On the other stuff... you link..

    The person that wrote that write up is an opinionated  narcissist. 

    Programming and learning come in may forms. Humans learn by mimicking. Humans learn by example. From there.... there may be a jump of point to dedicated study to learn and collect a deeper understand... but even then. One may still choose to do the things this person states are unnecessary.

    How can this writer tell you as an individual with is or what is not unnecessary?   Some people like myself will leave breadcrumbs in my programs to help me remember what I did and why... I also leave loads of comments and links to examples that helped me find solutions to a tough problem.

    People like this writer have nothing better to do is bash people that don't strive for the same level of existence that they do.  So they call people less then they are cargo programmers ... I call people that call names Useless. Sadly I can't get my time back from reading that. 

    Monday, July 6, 2020 2:01 PM
  • User2130491911 posted

    Hi DA924 I tried what you had here and it was a no go still get error. My guess is that what I wanted to do can't be done. Maybe view models require something special that I don;t have added to the base program??? Who knows..

    This is what I got from your sample and links

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.Models;
    using RMRP_SELF_ASSESSMENT.ViewModels;
    
    
    namespace RMRP_SELF_ASSESSMENT.Controllers
    {
        public class QA_RMRPController : Controller
        {
            // GET: QA_RMRP
            public ActionResult Question_Intake()
            {
                RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
    
                using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities())
                {
    
                    var results = RMRP_DB.COUNTY_LOCATION_TBL.ToList();
    
                    RMRP_DDL_VM.CountyLocationDropDownList drplist = new List<SelectListItem>();
    
                    foreach (var item in results)
                    {
    
                        var sli = new SelectListItem();
                        sli.Value = item.ID.ToString();
                        sli.Text = item.Location;
                        drplist.Add(sli);
                       
                    }
                    return RMRP_DDL_VM;
                }
            }
        }
    }

    THis is the view model 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.Models;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS
        {
    
            public List<SelectListItem> CountyLocationDropDownList { get; set; }
    
            public partial class COUNTY_LOCATION_TBL
            {
                public int ID { get; set; }
                public string LOCATION { get; set; }
    
                
            }
    
    
            public List<SelectListItem> ContactLocationDownList { get; set; }
    
            public partial class CONTACT_LOCATION_NUMBER_TBL
            {
                public int ID { get; set; }
                public string CONTACT_LOCATION { get; set; }
    
    
            }
    
        }
    }

    I get the following errors  the system seems not to like RMRP_DDL_VM.CountyLocationDropDownList drplist = new List<SelectListItem>();

    Not sure what to do what this one 

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0118	'RMRP_DDL_VM' is a variable but is used like a type	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	24	Active
    Error	CS0029	Cannot implicitly convert type 'RMRP_SELF_ASSESSMENT.ViewModels.RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS' to 'System.Web.Mvc.ActionResult'	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	35	Active
    Message	IDE0017	Object initialization can be simplified	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	29	Active
    

    Looking up the errors seems to yield that the system does not like this paert

    Monday, July 6, 2020 4:06 PM
  • User475983607 posted

    It's very painful to help you.  You continue to make the same coding mistakes even when we explain the mistake. 

    I took the liberty to change your RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS class.  I removed the partial classes and fixed the property definitions.  There's no logical reason for the partial classes within the View Model and the SelectList type already contains a List of options.  There's not reason to create a List<SelectList> property.

    public class RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS
    {
        public SelectList CountyLocationDropDownList { get; set; }
        public SelectList ContactLocationDownList { get; set; }
    }

    I update the Question_Intake action to populate the SelectList CountyLocationDropDownList property directly.

    public ActionResult Question_Intake()
    {
        RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
        using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities()) 
        {
            RMRP_DDL_VM.CountyLocationDropDownList = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "LOCATION");
        }    
        return View(RMRP_DDL_VM);
    }

    I'm not sure how to populate the ContactLocationDownList property.  You should be able to follow the same pattern as the CountyLocationDropDownList property.

    Monday, July 6, 2020 4:10 PM
  • User2130491911 posted

    I will give this a try.

    View models are painful to understand mate.. which may be a subject of the pain. I'm causing you. \

    I followed what was posted and got those errors. I am looking a video just now  the web that is doing the same thing.

    Is there a 3rd party add on that would make this easier I wonder?

    Well as always think you for all the help

    Monday, July 6, 2020 5:03 PM
  • User475983607 posted

    Add a property to hold the IDs if you want to use the same view model for posting user values.  Keep in mind, this pattern has been explained to you many times.

    public class RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS
    {
        public CountyLocationId {get; set;}
        public SelectList CountyLocationDropDownList { get; set; }
        
        public ContactLocationId {get; set;}
        public SelectList ContactLocationDownList { get; set; }
    }

    Monday, July 6, 2020 5:19 PM
  • User2130491911 posted

    I took what you posted and added to the application replacing the source I had written

            public ActionResult Question_Intake()
            {
                RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
                using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities())
                {
                    RMRP_DDL_VM.CountyLocationDropDownList DDL_COUNTY_LOV = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "LOCATION");
                }
                return View(RMRP_DDL_VM);
            }

    Error:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	CS0118	'RMRP_DDL_VM' is a variable but is used like a type	RMRP_SELF_ASSESSMENT	C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs	21	Active
    

    I think we a pretty convincing case that view models can be used to make dropdown list. Yes?

    1>------ Rebuild All started: Project: RMRP_SELF_ASSESSMENT, Configuration: Debug Any CPU ------
    1>C:\APP_DEV\RMRP_SELF_ASSESSMENT\RMRP_SELF_ASSESSMENT\Controllers\QA_RMRPController.cs(21,17,21,28): error CS0118: 'RMRP_DDL_VM' is a variable but is used like a type
    ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
    

    Or maybe my visual studio is buggered out??  But something is broken. 


    Monday, July 6, 2020 5:25 PM
  • User2130491911 posted

    I still get lost when you write about holding values.  I am still not clear on when a user would post a value to the dropdown list. But U I will add this to the view model since you say it would be helpful in this case.

    I think it would make more sense if this was for a data entry screen of some sort but I won;t question it.. At this point I just want something to work. Thank you!

    Monday, July 6, 2020 5:31 PM
  • User475983607 posted

    Or maybe my visual studio is buggered out??  But something is broken. 

    There is nothing wrong with Visual Studio and nothing is broken except your understanding.   It's truly baffling that you make the same coding mistakes over and over,

    public ActionResult Question_Intake()
    {
        RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
        using (RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities())
        {
            RMRP_DDL_VM.CountyLocationDropDownList = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "LOCATION");
        }
        return View(RMRP_DDL_VM);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 6, 2020 5:51 PM
  • User475983607 posted

    AppDev01

    I still get lost when you write about holding values.  I am still not clear on when a user would post a value to the dropdown list. But U I will add this to the view model since you say it would be helpful in this case.

    I think it would make more sense if this was for a data entry screen of some sort but I won;t question it.. At this point I just want something to work. Thank you!

    I recommend that you go through beginning level tutorials which cover fundamental like submitting a form and model binding.  

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started

    I think you'll also be interested in learning basic HTTP.

    https://www.w3schools.com/tags/ref_httpmethods.asp

    Lastly, bookmark the C# programming guide and take the time to look up C# syntax.  The forum assumes posters understand basic types, how to create class, how to populate a class, and how to assign a value to a class property.  

    Monday, July 6, 2020 6:00 PM
  • User2130491911 posted

    Ummm I followed what you posted... so the mistake was in your example as well. Unless I mis-read your example.

    And you keep on stating this stuff a about know this basic this and that.. that is not the issue, The issue is all with in the view model situation. 

    When something is not clear I follow what I read. The mistake may be mistakes made by the producer of the tutorial that I may not catch or know better.

    The forums are great and the more senior people are pretty cool to share what they know with people that know less then they do.

    The constant misrepresentation of some one asking for help is not kind.. but I can take it because I am not a developer like you guys. My goals are not the same and I don't comment these things to memory. All my application are road maps for the next. I build elements that I then go back and use in the next program if they are needed.

    I think what I am getting from you is that people that don't live and breathe this stuff are less than welcomed as this is a place to what? Not ask questions??? But know the answers to the questions you ask... if that is the case.. I don't think that makes any sense.

    With all of that I say thank you and I will try this again. And be sure I have read alot on this view model stuff and I know for certain this is a concept that no mater how much I read on it do examples... I will never understand.  There are things in life that are like that.

    On the UI stuff come on mate.. Get real please. Not every one designs the same way. Just because you make your List of values something to edit does not mean that someone is lacking knowledge on when and where to use that tool. 

    This design I am trying to do has zero to do with data entry.. So there is no need to edit as all the edits would happen in the database away from the application. All I want to know was if it was possible to have all the applications dropdownlist come from a view model. How that exposes me to the idea of being a know nothing cargo person  beggars belief.

    Its pretty rude to boot. Again thanks for the help... you can stow the opinions though.  Well back to work trying to figure all this out.

    Monday, July 6, 2020 6:33 PM
  • User475983607 posted

    Ummm I followed what you posted... so the mistake was in your example as well. Unless I mis-read your example.

    You are correct the mistake is in my initial example.  Which I fixed.

    Monday, July 6, 2020 6:39 PM
  • User2130491911 posted

    Its all Kool & the Gang... take care. 

    Monday, July 6, 2020 6:42 PM
  • User2130491911 posted

    Can I ask you one more Question?

    THis is my new Error

    Exception thrown: 'System.Web.HttpException' in System.Web.dll
    An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
    DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'ID'.

    I got rid of the using statement because I was getting an error about dbcontext was disposed or something... so I removed the using as I only had it there because it was in an earlier example.

    This is the view model file.. you said to me that I did not need the partial classes on there but now the system cannot see that there is an ID field and I suspect that it would show the same error for location. Not sure what is going on...

    using System.Web;
    using System.Web.Mvc;
    using RMRP_SELF_ASSESSMENT.Models;
    
    namespace RMRP_SELF_ASSESSMENT.ViewModels
    {
        public class RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS
        {
            public SelectList CountyLocationDropDownList { get; set; }
            public SelectList ContactLocationDownList { get; set; }
    
        }
    }

    So now I have this and this is where the error is

    Using statement was removed:

            public ActionResult Question_Intake()
            {
                RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS RMRP_DDL_VM = new RMRP_DROP_DOWN_LIST_VIEWMODEL_CLASS();
                RMRP_DBE_Entities RMRP_DB = new RMRP_DBE_Entities();
                
                    RMRP_DDL_VM.CountyLocationDropDownList = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "Location");
                
                return View(RMRP_DDL_VM);
            }

    This is where the error occurs

                <div>Please select your city/county:  </div>
                <br />
                @Html.DisplayNameFor(model => model.CountyLocationDropDownList)
                @Html.DropDownListFor(model => model.CountyLocationDropDownList, new SelectList(Model.CountyLocationDropDownList, "ID", "LOCATION"), "Select Your Location")
    
                <br />

    Is saying there is no ID... now you had be remove that info from my view model.... Mgebhard... you are not messing  with me are you :) I'm sure you are not...

    I mean I had those fields in the view model...now the system is saying it can find the ID field. Can anyone see what could be the issue??? :(

    My search for a solution on this is not turning anything  usable.  Thanks

     I am so burnt out on this lol

    WHen I step into the source I can see that there are values in the select list... they just can't display in the razor form... :(

    Monday, July 6, 2020 8:47 PM
  • User2130491911 posted

    okay looking through and older application that I wrote.. I used a viewbag vs this view model garbage... should I just forgo the view bugged view model and just access the table directly and use a view bag.

           @Html.DropDownListFor(model => model.RES_VEH_ID, (SelectList)ViewBag.VehList, " - PLEASE SELECT A VEHICLE - ", new { @class = "form-control", @onchange = "GetVehicleInformation(this.value)" })

    This does not require that silly ID stuff. I was hoping that I could learn something new with the view models but each fix adds a new error that I have never seen before...so clearly this is way to advance... unless this fix is simple I think this may be my last attempt at this view model thing....

    Monday, July 6, 2020 9:22 PM
  • User475983607 posted

    Is saying there is no ID... now you had be remove that info from my view model.... Mgebhard... you are not messing  with me are you :) I'm sure you are not...

    You are mistaken.  RMRP_DB is your entities not your view model.  You have not shared the COUNTY_LOCATION_TBL entity.

    RMRP_DB.COUNTY_LOCATION_TBL

    click on the COUNTY_LOCATION_TBL with your mouse then press "F12".  This should navigate to your entities class.  Find the ID field and replace "ID" with the entity ID whatever that name is.  You might have to do the same with "Location". 

    RMRP_DDL_VM.CountyLocationDropDownList = new SelectList(RMRP_DB.COUNTY_LOCATION_TBL, "ID", "Location");

    Again, all you are doing is using entity framework to query the database.  The results of the query populate the View Model which the view uses to populate the select element.

    Monday, July 6, 2020 9:30 PM
  • User1120430333 posted

    I get the following errors the system seems not to like RMRP_DDL_VM.CountyLocationDropDownList drplist = new List<SelectListItem>();

    It's named CountyLocationDropDownList and not the other name above.\

    Monday, July 6, 2020 9:34 PM
  • User2130491911 posted

    Hey thanks for all the help but view models are not for me... way too advance.

    So I am just going to put this thread to bed. I have been at it for about  two week and what I discovered in the type of programs that get assigned to write I can avoid them when doing drop down list. For project that require them we will just hire an outside resource as my brain cannot wrap itself around this concept burrito.  I learned a lot though so I do appropriate all the help.  Take care. and Thanks!

    Tuesday, July 7, 2020 9:38 PM
  • User1120430333 posted

    Hey thanks for all the help but view models are not for me... way too advance.

    So I am just going to put this thread to bed. I have been at it for about  two week and what I discovered in the type of programs that get assigned to write I can avoid them when doing drop down list. For project that require them we will just hire an outside resource as my brain cannot wrap itself around this concept burrito.  I learned a lot though so I do appropriate all the help.  Take care. and Thanks!

     The VM implementation and  usage  is OO 101 that any decent .NET developer should be able to understand. 

    Wednesday, July 8, 2020 1:11 AM
  • User550915133 posted

    Let's see if I can bring a little clarity here.

    VIEW:
    The view is the template that generates the HTML that is sent to the browser.
    Sometimes the view needs some data in order to be useful, for example the values for a dropdownlist. Those values are sent using a view model.

    MODEL:
    The model when talking about MVC is actually a view model. It is simply a class you write that has enough information in order for the view to be rendered.
    You decide what the class should be named, maybe you want to use a naming convention where you have "VM" at the end of the class name, or something else. You decide.

    CONTROLLER:
    The controller (or rather the methods/actions) is the one that gets called by the browser. Common things it does is validate inputs and return a view if all is OK.
    If the view needs a view model it is up to the controller to set it up and send it to the view.


    If it is a small application or just a proof-of-concept you can perhaps get away with using the database model as a view model, but there are downsides to this:
    you add properties to the database model that shouldn't be in the database so you add [NotMapped] to them and the next view you're designing needs different properties so you add those also and all of a sudden you have a bunch of properties that just obfuscates the purpose of the database model.
    You are also tying the view to the database making future changes harder, etc.
    (This is also the separation-of-concerns thing - the view shouldn't be concerned about what the database looks like, or even that you have a database.)

    Another benefit when using view models is when you want information from more than one database table - just have the controller get the information from the database and set the view model properties as needed.

    Some blog posts use the "database model as a view model", this is often because they are writing about something else and creating a real view model would make the blog post longer.
    In other words, they are using the "proof-of-concept" style.

    Wednesday, July 8, 2020 1:27 PM