2017-08-25 50 views
0

我有一個方法,基於在下拉列表中創建的對象列表在我的數據庫中進行搜索,但在3個表中返回,但是從它的3個表我很困惑,最後如何返回。 我是MVC的新手。 請幫忙!!在ASP.net中的一個數據庫中的3個表中搜索MVC

public ActionResult Search(string searchBy, string list) 
    { 

     var ola = new object[] { "Exchange", "Business Sector", "Country", "Company Name" }; 
     ViewBag.list = new SelectList(ola); 


     var exchange = from a in db.Exchange_tbl 
         select a; 

     if (!String.IsNullOrEmpty(searchBy)) 
     { 
      if (list.Equals("Exchange")) 
      { 
       exchange = exchange.Where(a => a.exchangeName.Contains(searchBy)); 
      } 
     } 


     var businessSector = from s in db.BusinessSector_tbl 
          select s; 
     if (!String.IsNullOrEmpty(searchBy)) 
     { 
      if (list.Equals("Business Sector")) 
      { 
       businessSector = businessSector.Where(s => s.businessSectorDesc.Contains(searchBy)); 
      } 
     } 

     var country = from x in db.Country_tbl 
         select x; 
     if (!String.IsNullOrEmpty(searchBy)) 
     { 
       if (list.Equals("Country")) 
       { 
        var countries = db.Country_tbl.ToList(); 
        List<int> countryIds = countries.Where(x => x.countryName.ToLower().Contains(searchBy.ToLower())).Select(x => x.countryID).ToList(); 
        List<int> companyIds = db.countrycompviews.Where(x => countryIds.Contains(x.countryID)).Select(x => x.companyID).ToList(); 
        country = country.Where(s => companyIds.Contains(s.countryID)); 
       } 
     } 


     return View(exchange.Union(country).ToList()); 
    } 
+0

您是否試過使用ViewBag? – N1gthm4r3

+0

1]您可以將結果發送到'ViewBag.SearchResults'。在你看來,你可以有一個開關盒,並投射並相應地顯示它們。或者2],您可以創建一個容器模式,包含Exchange列表,BusinessSector列表等屬性,並根據您選擇的項目在視圖中顯示它們。我認爲第二個會很好,因爲如果您的要求發生變化,您可以顯示多個列表 – adiga

回答

0

創建一個像這樣的容器模型。

public class SearchResult 
{ 
    public string SelectedList { get; set; } 

    public IList<Exchange> Exchanges { get; set; } 

    public IList<BusinessSector> BusinessSectors { get; set; } 

    public IList<Country> Countries { get; set; } 
} 

在你的控制器,你已經詢問所有表後,填寫所有列表:

SearchResult searchResult = new SearchResult { 
    BusinessSectors = businessSector, 
    Countries = country, 
    Exchanges = exchange, 
    SelectedList = list 
} 

// logic to get the selectlist for the dropdown 

return View(searchResult); 

在你看來,你的觀點的頂部添加@model Models.SearchResult

@switch (model.SelectedList) 
{ 
    case "Exchange": 
    // logic to loop through display model.Exchanges in a table or something 

    case "Business Sector": 
    // logic to loop through display model.BusinessSectors 

    case "Country": 
    // logic to loop through display model.Countries 
} 
相關問題