How to deal with many possible values to make a query?

后端 未结 3 1867
囚心锁ツ
囚心锁ツ 2021-01-23 03:06

I\'m building an MVC app in which the user will have the possibilities of using a lot of filters to get exactly what he wants.

Here\'s an overview of those filters based

3条回答
  •  梦谈多话
    2021-01-23 03:48

    Here's a way you could handle your problem.

    First, create a ViewModel with your search parameters.

    public class FilterViewModel
    {
        public string ObjName { get; set; }
        public string ObjType { get; set; }
        public string OtherType { get; set; }
    }
    

    In your controller, pass this to the view.

    public virtual ActionResult SearchResults()
    {
        return View(new FilterViewModel());
    }
    

    In your SearchResults.cshtml you need to encode the model to a json and then use an ajax call to filter your results. Assumming there's a button with btnFilterResults id. This is going to load the results from a partial view (that should be your table) using ajax.

    
    

    Finally, in your controller you can get the results:

    [HttpGet]
    public virtual ActionResult LoadTableReporteGeneral(string viewModel)
    {
        var filterOptions = JsonConvert.DeserializeObject(viewModel);
        var query = from t in db.YourTableName
                    select t;
         //This returns an IQueryable with all of your data, no filtering yet.
    
         //Start filtering.
         if(!String.IsNullOrEmpty(filterOptions.ObjName))
         {
             query = query.Where(x => x.ObjName == filterOptions.ObjName);
         }  
         if(!String.IsNullOrEmpty(filterOptions.ObjType ))
         {
             query = query.Where(x => x.ObjType == filterOptions.ObjType );
         }  
         //and so on. 
         //Finally return a partial view with your table. 
         return PartialView(MVC.Shared.Views._YourTableName, query);
    }
    

    Note: I'm using T4MVC and Json.Net packages.

    Hope this helps.

提交回复
热议问题