How can I keep the the logic to translate a ViewModel's values to a Where clause to apply to a linq query out of My Controller?

Posted by Mr. Manager on Stack Overflow See other posts from Stack Overflow or by Mr. Manager
Published on 2013-06-25T18:50:26Z Indexed on 2013/06/25 22:21 UTC
Read the original article Hit count: 195

Filed under:
|
|

This same problem keeps cropping up. I have a viewModel that doesn't have any persistent backing. It is just a ViewModel to generate a search input form.

I want to build a large where clause from the values the user entered. If the Action Accepts as a parameter SearchViewModel How do I do this without passing my viewModel to my service layer? Service shouldn't know about ViewModels right? Oh and if I serialize it, then it would be a big string and the key/values would be strongly typed.

SearchViewModel this is just a snippet.

[Display(Name="Address")]
  public string AddressKeywords { get; set; }

        /// <summary>
        ///     Gets or sets the census.
        /// </summary>
        public string Census { get; set; }

        /// <summary>
        ///     Gets or sets the lot block sub.
        /// </summary>
        public string LotBlockSub { get; set; }

        /// <summary>
        ///     Gets or sets the owner keywords.
        /// </summary>
        [Display(Name="Owner")]
        public string OwnerKeywords { get; set; }

In my controller action I was thinking of something like this. but I would think all this logic doesn't belong in my Controller.

ActionResult GetSearchResults(SearchViewModel model){
    var query = service.GetAllParcels();
    if(model.Census != null){
    query = query.Where(x=>x.Census == model.Census);
    }
    if (model.OwnerKeywords != null){
    query = query.Where(x=>x.Owners == model.OwnerKeywords);
    }
    return View(query.ToList());
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc