通过输入价格范围,来筛选汽车,主要方法是通过点击“查询”按钮,触发chaxun()方法,利用Jquery和JS获取输入的值,然后为相应的div加载相应的动作,通过更改路由的路径,以此来实现筛选车辆,然后将筛选出来的车辆显示在相应的div上
1、Models public class CarBF { private MyDBDataContext _context = new MyDBDataContext(); public List<car> Select(decimal Low,decimal Upp) //通过价格范围查询 { var query = _context.car.Where(P=>P.price>Low&&P.price<Upp); //价格范围 if (query.Count() > 0) { return query.ToList(); } else { return null; } } } 2、Controllers namespace MvcApplication2.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() //主要的界面 { return View(); } public ActionResult Select(decimal Low,decimal Upp) //筛选汽车 { List<car> list =new CarBF().Select(Low,Upp); return PartialView(list);//为相应的div加载分部视图 } } } 3、Views Index: @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> 最低价格:@Html.TextBox("Low") <br> 最高价格:@Html.TextBox("Upp") <br> <input id="Submit2" type="button" value="查询" onclick="chaxun()" /> </div> <div id="cx"></div> </body> </html> <script src="~/Script/jquery-1.11.2.min.js"></script> <script> function chaxun() { var a = document.getElementById("Low").value;//获取到Id为Low对象的值(JavaScript方法) var b = $("#Upp").val();//获取到Id为Upp对象的值(Jquery方法) $("#cx").load("/find/Home/Select/" + a + "/" + b);//为Id为cx的对象加载前缀为find,控制器为Home,动作为Select的动作,并把获取到的两个值作为参数传过去,中间的"/"不能乱写,必须和路由里写的格式一样 } </script> Select: @using MvcApplication2.Models; @model List<car> <div> <ul> @foreach(car data in Model) { <li>@data.name</li> } </ul> </div> 4、路由设置 public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default1", url: "find/{controller}/{action}/{low}/{upp}", //路由格式 defaults: new { controller = "Home", action = "Index", low = 0, upp = 100 } //defaults 默认
); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
效果图: