4
\$\begingroup\$

In the index view a user can search with any combination of one to all of the following parameters: firstname, lastname or ssn. The found search results are displayed in the search results view. In my HomeOfficeController I have written the code like this, but most of the code is repeating.

Can someone suggest a neater way of writing this code?

    [HttpPost]
    public ActionResult Index(HomeOfficeViewModel viewModel)
    {
        TempData["FirstName"] = viewModel.FirstName;
        TempData["LastName"] = viewModel.LastName;
        TempData["SSN"] = viewModel.FullSsn;
        return RedirectToAction("SearchResults", "HomeOffice");
    }

    public ActionResult SearchResults(HomeOfficeViewModel viewModel, UserSessionContext sessionContext)
    {
        TempData.Keep();
        if (TempData["FirstName"] != null)
        { viewModel.FirstName = TempData["FirstName"].ToString(); }
        if (TempData["LastName"] != null)
        { viewModel.LastName = TempData["LastName"].ToString(); }
        if (TempData["SSN"] != null)
        { viewModel.FullSsn = TempData["SSN"].ToString(); }

        if (viewModel.FirstName != null && viewModel.LastName == null && viewModel.FullSsn == null)
        {
            var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                               {
                                                   FullSsn = p.Ssn,
                                                   FullName = p.FirstName + " " + p.LastName,
                                                   UserId = p.UserId,
                                                   AccountVerified = p.AccountVerified
                                               };
                ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate, 
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "First Name searched does not exist in our records");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName == null && viewModel.LastName != null && viewModel.FullSsn == null)
        {
            var ph = _policyHolderRepository.Where(x => x.LastName == viewModel.LastName).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                               {
                                                   FullSsn = p.Ssn,
                                                   FullName = p.FirstName + " " + p.LastName,
                                                   UserId = p.UserId,
                                                   AccountVerified = p.AccountVerified
                                               };
                ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "Last Name searched does not exist in our records");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName == null && viewModel.LastName == null && viewModel.FullSsn != null)
        {
            var ph = _policyHolderRepository.Where(x => x.Ssn == viewModel.FullSsn).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                    {
                                        FullSsn = p.Ssn,
                                        FullName = p.FirstName + " " + p.LastName,
                                        UserId = p.UserId,
                                        AccountVerified = p.AccountVerified
                                    };
                ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "SSN searched does not exist in our records");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn == null)
        {
            var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName && x.LastName == viewModel.LastName).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                               {
                                                   FullSsn = p.Ssn,
                                                   FullName = p.FirstName + " " + p.LastName,
                                                   UserId = p.UserId,
                                                   AccountVerified = p.AccountVerified
                                               };
                ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
                ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "Combination of First Name and Last Name searched does not exist in our records");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName != null && viewModel.LastName == null && viewModel.FullSsn != null)
        {
            var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName && x.Ssn == viewModel.FullSsn).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                    {
                                        FullSsn = p.Ssn,
                                        FullName = p.FirstName + " " + p.LastName,
                                        UserId = p.UserId,
                                        AccountVerified = p.AccountVerified
                                    };
                ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
                ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "Combination of First Name and SSN searched does not exist in our records");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName == null && viewModel.LastName != null && viewModel.FullSsn != null)
        {
            var ph = _policyHolderRepository.Where(x => x.LastName == viewModel.LastName && x.Ssn == viewModel.FullSsn).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                    {
                                        FullSsn = p.Ssn,
                                        FullName = p.FirstName + " " + p.LastName,
                                        UserId = p.UserId,
                                        AccountVerified = p.AccountVerified
                                    };
                ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
                ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "The Customer Name and SSN were not found.  Please revise your search.");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn != null)
        {
            var ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName && x.LastName == viewModel.LastName && x.Ssn == viewModel.FullSsn).ToList();
            if (ph.Count != 0)
            {
                var searchresults = from p in ph
                                    select new SearchResultsViewModel
                                    {
                                        FullSsn = p.Ssn,
                                        FullName = p.FirstName + " " + p.LastName,
                                        UserId = p.UserId,
                                        AccountVerified = p.AccountVerified
                                    };
                ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
                ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
                ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
                return View("SearchResults", new SearchResultsViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                    SearchResults = searchresults.ToList()
                });
            }
            else
            {
                ModelState.Clear();
                ModelState.AddModelError("Error", "Combination of First Name, Last Name and SSN searched does not exist in our records");
                var homeOfficeViewModel = new HomeOfficeViewModel()
                {
                    PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                    LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
                };
                return View("Index", homeOfficeViewModel);
            }
        }

        else if (viewModel.FirstName == null && viewModel.LastName == null && viewModel.FullSsn == null)
        {
            ModelState.AddModelError("User Error", "Atleast enter one of the search criteria");
            var homeOfficeViewModel = new HomeOfficeViewModel()
            {
                PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
            };
            return View("Index", homeOfficeViewModel);
        }

        else
        {
            return View();
        }
    }
\$\endgroup\$
0
2
\$\begingroup\$

You could look at putting the core of the logic into a service layer. This will help keep the controller skinny as well as help with writting unit tests as well. I wrote this in notepad so it's not tested but gives an idea of what I mean.

This could be done even more by things such as providing a way to expose properties for the displaymessage rather than having it hard coded to '<<< field >>>' etc This would give more power to the view to determine how to render the message.

public ActionResult Index(HomeOfficeViewModel viewModel)
{

    HomeOfficeQueryService service = new HomeOfficeQueryService();
    List<HomeOfficeViewModel> searchResults = new List<HomeOfficeViewModel>();

    try
    {
        if(!ModelState.IsValid())
        {
            throw new NoResultsException(""); 
        }

        var critera = service.GetCriteria(viewModel);
        searchResults = service.GetQuery(criteria).ToList();            
    }
    catch(NoResultsException ex)
    {
        if(ex.GetMessage().Length() > 0)
            ModelState.AddModelError("Error", ex.GetMessage());         
    }
    finally
    {
        return View("SearchResults", new SearchResultsViewModel()
            {
                PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate, 
                SearchResults = searchResults
            });     
    }
}
class HomeOfficeQueryCriteria 
{
    public Predicate<HomeOfficeViewModel> Criteria { get; set; }
    public string EmptySearchMessage { get; set; }
    public string DisplayMessage { get; set; }
}

class HomeOfficeQueryService()
{
    private Repository<T> _policyHolderRepository;

    public HomeOfficeQueryService(Repository<T> policyHolderRepository)
    {
        _policyHolderRepository = policyHolderRepository;
    }

    public HomeOfficeQueryCriteria GetCriteria(HomeOfficeViewModel viewModel)
    {
        if(!string.isNullOrWhiteSpace(viewModel.FirstName) && string.isNullOrWhiteSpace(viewModel.LastName) && string.isNullOrWhiteSpace(viewModel.FullSsn))
        {
            return new HomeOfficeQueryCriteria()
            {
                Criteria = (x) => x.FirstName == viewModel.FirstName,
                EmptySearchMessage = "First Name searched does not exist in our records".
                DisplayMessage = "<<< First Name >>> is '" + viewModel.FirstName + "'";
            };
        }
        else if (viewModel.FirstName == null && viewModel.LastName != null && viewModel.FullSsn == null)
        {
            // fill out more criteria here
        }
        else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn == null)
        {
            // fill out more criteria here
        }
        else if (viewModel.FirstName != null && viewModel.LastName != null && viewModel.FullSsn != null)
        {
            // fill out more criteria here
        }
        else
        {
            // Any more conditions here
        }

    }

    public IQueryable<SearchResultsViewModel> GetQuery(HomeOfficeQueryCriteria arg) where T : HomeOfficeViewModel
    {
        var items = _policyHolderRepository.Where(x => arg.Criteria);

        if(items.Any()
        {
            var query = var searchresults = from p in ph
                        select new SearchResultsViewModel
                                   {
                                       FullSsn = p.Ssn,
                                       FullName = p.FirstName + " " + p.LastName,
                                       UserId = p.UserId,
                                       AccountVerified = p.AccountVerified
                                   };


            return query;
        }
        else
        {
            throw NoResultsException(arg.EmptySearchMessage);
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

This is roughly how I would refactor it (note: I have not tried to compile this so I'm sure some tweaking will be needed).

public ActionResult SearchResults(HomeOfficeViewModel viewModel, UserSessionContext sessionContext)
{
    TempData.Keep();
    if (TempData["FirstName"] != null)
    { viewModel.FirstName = TempData["FirstName"].ToString(); }
    if (TempData["LastName"] != null)
    { viewModel.LastName = TempData["LastName"].ToString(); }
    if (TempData["SSN"] != null)
    { viewModel.FullSsn = TempData["SSN"].ToString(); }

    if (viewModel.FirstName == null && viewModel.LastName == null && viewModel.FullSsn == null)
    {
        ModelState.AddModelError("User Error", "Atleast enter one of the search criteria");
        var homeOfficeViewModel = new HomeOfficeViewModel()
        {
            PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
            LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
        };
        return View("Index", homeOfficeViewModel);
    }
    else
    {

        var ph = _policyHolderRepository;
        if (viewModel.FirstName != null)
        {
            var ph = ph.Where(x => x.FirstName == viewModel.FirstName);
            ViewData["FirstName"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
        }
        if (viewModel.LastName != null)
        {
            var ph = ph.Where(x => x.LastName == viewModel.LastName);
            ViewData["LastName"] = "<<< Last Name >>> is '" + viewModel.LastName + "'";
        }
        if (viewModel.FullSsn != null)
        {
            var ph = ph.Where(x => x.Ssn == viewModel.FullSsn);
            ViewData["SSN"] = "<<< Social Security No. >>> is '*****" + viewModel.FullSsn.Substring(5) + "'";
        }
        var searchresults = from p in ph.ToList()
                                    select new SearchResultsViewModel
                                    {
                                        FullSsn = p.Ssn,
                                        FullName = p.FirstName + " " + p.LastName,
                                        UserId = p.UserId,
                                        AccountVerified = p.AccountVerified
                                    };
        if (searchresults.Count != 0)
        {
            return View("SearchResults", new SearchResultsViewModel()
            {
                PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate,
                SearchResults = searchresults.ToList()
            });
        }
        else
        {
            ModelState.Clear();
            ModelState.AddModelError("Error", "Your search returned no results.  Please revise your search.");
            var homeOfficeViewModel = new HomeOfficeViewModel()
            {
                PolicyOwnerFirstName = sessionContext.LoggedInUserFullName,
                LastLoggedOnDate = sessionContext.LoggedInUserLastLoggedOnDate
            };
            return View("Index", homeOfficeViewModel);
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ var ph = ph.Where(x => x.FirstName == viewModel.FirstName); var ph = ph.Where(x => x.LastName == viewModel.LastName); var ph = ph.Where(x => x.Ssn == viewModel.FullSsn); why are we doing this? \$\endgroup\$ – Theja Aug 5 '11 at 16:20
  • \$\begingroup\$ @Theja - What it does is build up your query dynamically. So for instance say that the user entered a first name and a last name but not a SSN. Then the first two if blocks get executed. The first one makes your query look like this -> _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName). Then the second if get executed, making your query look like this -> _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName).Where(x => x.LastName == viewModel.LastName). The query builds up until ph.ToList() is called and then the query is executed. \$\endgroup\$ – Becuzz Aug 5 '11 at 16:28
  • \$\begingroup\$ (cont.) This lets you build up the query with only the parts that are needed and lets you disregard the parts that aren't relevant (the SSN in this case). You may want to look up how LINQ does lazy execution of queries. \$\endgroup\$ – Becuzz Aug 5 '11 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.