2016-06-14 16 views
0

我對.NET MVC非常新,並且已經遵循these tutorials。我開始嘗試爲自己創建一些東西,並參考教程獲取指導。使用.NET MVC與兩種模​​型進行搜索

雖然試圖實現搜索功能,但我努力讓第二個搜索框起作用。我有兩個型號,配置文件和目錄:

public class Profile { 

    public int ProfileID { get; set; } 
    [Required] 
    public string Location { get; set; } 
    public virtual List<Category> Categories { get; set; } 
} 

public class Category { 
     public int CategoryID { get; set; } 
     public string Name { get; set; } 
     public string Value { get; set; } 
} 

我有我的第一次搜索工作的罰款,這需要對配置文件位置屬性的文本輸入和搜索。不過,我想添加第二個搜索,在下拉列表中獲取所有類別的列表,並且用戶可以根據類別進行搜索。這裏是我到目前爲止的控制器代碼:

public ActionResult Index(string searchCategory, string searchString) 
    { 
     var CategoryList = new List<string>(); 

     var CategoryQuery = from d in db.Categories 
          orderby d.Name 
          select d.Name; 

     CategoryList.AddRange(CategoryQuery.Distinct()); 
     ViewBag.searchCategory = new SelectList(CategoryList); 

     var profiles = from p in db.Profiles 
         select p; 

     if (!String.IsNullOrEmpty(searchString)) { 
      profiles = profiles.Where(x => x.Location.Contains(searchString)); 
     } 

//**This is where I cannot figure out the right lambda expression 
     if (!String.IsNullOrEmpty(searchCategory)) { 
      profiles = profiles.Where(x => x.Categories.Contains(y => y.Name.Find(searchCategory))); 
     } 

     return View(profiles); 
    } 

我是很新的lambda表達式,並在第二個if語句,我知道我現在做的東西非常錯誤的,但我不能弄明白。

回答

1

嘗試改變內第二if你的代碼,這

profiles.Where(x => x.Categories.Any(y => y.Name==searchCategory)); 
0

List<SelectListItem>提供訪問下拉列表綁定:

// model class 
public class ModelClass 
{ 
    public List<SelectListItem> DropDownValues { get; set; } 
} 

List<Category>值到List<SelectListItem>

if (!String.IsNullOrEmpty(searchCategory)) { 
    // Equals ensure value comparison instead of possible reference 
    profiles = profiles.Where(x => x.Categories.Any(y => y.Name.Equals(searchCategory)); 

    DropDownValues = new List<SelectListItem>(); 

    // iterate through category list and pass values to SelectListItem 
    foreach (Categories cat in profiles) { 
     DropDownValues.Add(new SelectListItem() { Text = cat.Name, Value = cat.Value }); 
    } 
} 

CSHTML :

@Html.DropDownListFor(Model => Model.Value, ModelClass.DropDownValues); 

希望這個解決方案有很大幫助。

相關問題