Search code examples
asp.net-mvcmodel-view-controllermodelcontrollerviewmodel

Cast List<ViewModel> to ViewModel?


I want to preface this by saying I am new to working with models. Please forgive me if this question has a simple answer.

I have been struggling to revert a listed view model back to view model. To give some background, I have a search form being passed to a model coming from my ActionResult and am then getting a filter out the results.

[ Controller ]

    public ActionResult GetFilters(MembershipVM model)
    {
        var uDataList = new List<MembershipVM>();        
        
        model = _service.GetFilters(model);

        return View("SendEmail", model);
     }

[ Service ]

    public List<MembershipVM> GetFilters(MembershipVM model)
    {               
        var query = _context.Members.Where(f => f.Deleted == 0).AsQueryable();
        var members = _context.Members.ToList();

        query = query.Where(f => agencyTypes.Contains(f.AgencyType));
        
        var uDataList = new List<MembershipVM>();


        foreach (var member in members)
        {
            var uData = new MembershipVM();

            uData.Email = member.Email;
            uData.AgencyType = member.AgencyType;
            ...
            uDataList.Add(uData);
        }

        return uDataList;
    }
    

How can I cast the List from "_service.GetFilters" to MembershipVM? Is there a better/easier way to get the results as an object from the "_service.GetFilters" service?

Thanks so much in advance!

Daisy


Solution

  • I am not sure what you are trying to do here. First you get the results of your filter from this code:

    model = _service.GetFilters(model);
    

    And the definition of your method is this:

    public List<MembershipVM> GetFilters(MembershipVM model)
    

    So you would expect that this is a list of results. In short, a collection of results.

    Now if you want to pass it on your ActionResult as one entity only, then getting one of your results will do the trick:

    return View("SendEmail", model.Take(1).SingleOrDefault());
    

    But why do you need to pass one entity only? But that should work with your current requirement.