Контроллер для поиска с определенными параметрами


В индексе просмотра пользователь может осуществлять поиск с любой комбинацией от одного до всех следующих параметров: имя, фамилия или ССН. Найденные результаты поиска отображаются в результатах поиска. В моем HomeOfficeController я написал такой код, но большая часть кода повторяется.

Может кто-то предложить аккуратнее написать этот код?

    [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();
        }
    }


762
4
задан 5 августа 2011 в 02:08 Источник Поделиться
Комментарии
2 ответа

Вы могли бы посмотреть на размещение базовой логики на уровень сервисов. Это поможет сохранить тощий контроллер, а также помочь с написания модульных тестов, а также. Я написал это в блокноте, так это не проверял, но дает представление о том, что я имею в виду.

Это может быть сделано даже больше, такие вещи, как предоставление способ разоблачить свойства displaymessage в Вместо того, чтобы жестко '<<< поле >>>' и т. д. Это дало бы больше возможностей для просмотра, чтобы определить, как отображать сообщения.

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);
}
}
}

2
ответ дан 5 августа 2011 в 09:08 Источник Поделиться

Это примерно как я бы рефакторинг (примечание: Я не пытался скомпилировать это, поэтому я уверен, что некоторые настройки будут необходимы).

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);
}
}
}

0
ответ дан 5 августа 2011 в 03:08 Источник Поделиться