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

后端 未结 3 1841
囚心锁ツ
囚心锁ツ 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 04:04

    Why do you not use ModelBinder . I think it's very useful with your case. Please see below:

    _ I have a Model:

    public class Employee
    {
       public string Id { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public DateTime BirthDate { get; set; }
       public Address HomeAddress { get; set; }
    }
    

    and ModelBinder for Employee:

    public class EmployeeBinder : IModelBinder {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
                var emp = new Employee {
                                           Id = controllerContext.HttpContext.Request.Form["Id"],
                                           FirstName = controllerContext.HttpContext.Request.Form["FirstName"],
                                           LastName = controllerContext.HttpContext.Request.Form["LastName"],
                                           BirthDate = new DateTime(int.Parse(controllerContext.HttpContext.Request.Form["year"]),
                                               int.Parse(controllerContext.HttpContext.Request.Form["month"]),
                                               int.Parse(controllerContext.HttpContext.Request.Form["day"]))
                                       };
    
                return emp;
            }
        }
    

    Then Controller:

    public ActionResult Example(Employee emp) {
                return View(emp);
    }
    

    URL: http://localhost:1034/Home/Example?Id=1&LastName=lazycatit

提交回复
热议问题