2016-06-14 44 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); 

希望这个解决方案有很大帮助。

相关问题